To look at the importance of the ‘.’ Go back to our matrix C1 C1=([2 1 4; 4 3 6; 6 8 2]) Now try...

31

Transcript of To look at the importance of the ‘.’ Go back to our matrix C1 C1=([2 1 4; 4 3 6; 6 8 2]) Now try...

To look at the importance of the ‘.’

Go back to our matrix C1 C1=([2 1 4; 4 3 6; 6 8 2])

Now try to multiply C1 by C1

MESHGRID – spans a grid where points in a 2D matrix are assigned X and Y positions (or X, Y, Z for 3D)

EG, we want to calculate the cosine XbyY on an area limited by X=+-3 and Y=+-3.

Make the grid:

>>[X,Y]=meshgrid(-3:.1:3,-3:.1:3)

>>figure(1); Z=X.*Y; surf(X,Y,Z); colorbar %%%%%plots 3D figure and adds a %%%%colorbar

>>figure; Z=X.*Y; contourf(X,Y,Z); %%%%%2D figure filled contours

>>figure; Z=X.*Y; contour(X,Y,Z); %%%%%2D figure not filled contours

>> figure(2); Z=cos(X.*Y); surf(X,Y,Z);

Control flow of data…..

for i=1:10,

if i<5 a(i)=i*2;

elseif i==5 a(i)=i;

else a(i)=i/2;

end;

end

for i=10:15counter=counter+1if i<15 a(counter)=i*2; elseif i==15 a(counter)=i;elseif i==15 a(counter)=i;endend

>>while i>5;

>> a(i)=i*2;

>> i=i-1;

>>end

1) Create a vector X with values from 0 to 100 at intervals of 0.1

a) What is the 20th prime number in X

b) How many prime numbers are less than 1million

c) Factorize 646969323 (i.e. find the sequence of prime numbers resulting in this number when multiplied together)

2) Create the vector X=[65 114 101 32 121 111 117 32 99 114 97 122 121 63 10]

This is actually a message as each number represents a character or symbol.

Matlab uses ASCII coding and every character is assigned a value between 0 and 255.

a) Which sentence is represented by X?

b) What is the ascii code for ‘enter’

c) Using findstr what is the position of r in the above text?

X=[0:0.1:100];

t=primes(100); t(20)

t2=primes(1000000); size(t2)

f=factor(646969323);

x=[65 114 101 32 121 111 117 32 99 114 97 122 121 63 10]; s=char(x);

double('enter');

findstr(x,'r')

Often need to work with 3 or 4 D matrices, such as global atmosphere data or model generated data. Here is an example where we create a 3D space spanned by axes X,Y and Z. The first axis has values 0 to 360 with steps of 20. The second axis -90 to 90 with steps of 20 and finally an axis from 1990 to 1999.99 with steps of 1/12:

>>[X,Y,Z]=meshgrid(0:20:360,-90:20:90,1990:1/12:1999.99);

Generate the data…….

>>data=sin(X/1000).*cos(Y/100).*tanh(Z/2000);

a) What is the size of the matrix data? What is the minimum, maximum and mean value. In what position is the maximum?

b) Assume that the first 2 dimensions represent long and lat and the third is time and that the data are a scalar field eg global mean temps for a decade. How can you calculate the mean for each year?

c) It is common to make anomalies of data (deviation from the climate mean) by removing the mean for every month. i.e for every january we remove the mean of all the january months in the data (hear we have 10).

Jananom1999=janvalue1999-janmean(1990-1999);

plot the July anomaly for 1995 (help contour)

>> size(data)

ans =

10 19 120

>> min(data(:))

ans =

0

>> max(data(:))

ans =

0.26694353105108

>> mean(data(:))

ans =

0.11407671337753

>>[val,ind]=max(data(:)) >>[a,b,c,]=ind2sub(size(data),ind)

>>data2=reshape(data,10,19,12,10);>>size(data2)>>for y=1:10;>> Yr_data=squeeze(data2(:,:,:,y));>> Yr_data2(:,:,y)=mean(Yr_data,3);>>end

>>for m=1:12;>> mn_data=squeeze(data2(:,:,m,:));>> mn_climo(:,:,m)=mean(mn_data,3);>>end

>>for m=1:12;>> for yr=1:10>> Mn_anom(:,:,m,yr)=squeeze(data2(:,:,m,yr))-squeeze(mn_climo(:,:,m));>> end>>end

Reading ascii data w/o headerExample ctd>> clear all>> load examplectd.datWhos – examplectd in workspace which is 2138x5Ignores spaces. But if data is separated by comma and NO SPACE,

have to use function dlmread – data=dmlread(‘filename’,’,’);ALSO, if file has no extension have to include –ascii when

loading….. >>load ‘filename’ –ascii

Now, to split into variables:>>depth=examplectd(:,1); temp=examplectd(:,2);

salinity=examplectd(:,3); oxygen=examplectd(:,4); fluro=examplectd(:,5);

figure

subplot(1,4,1);plot(temp,-depth);

subplot(1,4,2);plot(salinity,-depth);

subplot(1,4,3);plot(oxygen,-depth);

subplot(1,4,4);plot(fluro,-depth);

figure,plot(salinity,temp)

title('salinity temp plot from BATS')

xlabel('salinity')

ylabel('temperature')

legend

Ascii-data with boring headerUse the function textread>>

[cruise,decimal,lat,lon,press,depth,temp]=textread('examplectdtxt.dat','%f %f %f %f %f %f %f','headerlines',2);

If csv>>

[cruise,decimal,lat,lon,press,depth,temp]=textread('examplectdtxt.dat','%f %*s %f %*s %f %*s %f %*s %f %*s %f %*s %f','headerlines',2);

The sign %* ensures that the data are not returned by the function.

The last part of the command ‘headerlines’,2 tells matlab to ignore the first 2 lines

Ascii-data with interesting header

>>fid=fopen(‘examplectdtxt.dat’,’r’);

>>dummy=fread(fid,’char’);

>>fclose(fid);

First we open file for reading (‘r’ is short for read). And a file identification number is given to fid. 2nd line, we read all the data as ascii code (numbers between 0 and 127) and then on 3rd line we close the file.

So we have now retrieved data and stored as numbers

>> char(dummy(1:1400)')Converts ascii code to characters.

Note the ‘ transpose. With whos you can see that dummy is a 86069x1 matrix (column vector). So to print data to look like in a text editor, need to transpose to 1x86069.

Now we want to extract information from the header: year, lat and lon.

Convert dummy into a row of characters

>> c=char(dummy');

Then use findstr to find the positions of the variables we want

>>temp_index=findstr('(C)',c);

>>ctd=str2num(c(temp_index+3:end));

saving ascii-data

the opposite function of load is save

>>load examplectd.dat;

>>save 'C:\Documents and Settings\juliet\ctd.asc' -ascii;

if –ascii is not included, matlab will save as a .mat file, which is fine for use in matlab but not anything else. the new file is twice as large as the old one as matlab saves in a different format (look at two files).

To separate data with column…

>>dlmwrite('ctd2.asc',examplectd,',');

This is more compressed, but can be slow.

A more readable form can be made using the fprintf function. Similar to textread

load 'examplectd.dat'

>> fid=fopen('ctd3.asc','wt')

>> fprintf(fid,'%4d %6.3f %6.3f %6.2f %5.3f\n',examplectd');

>> fclose(fid)

>>load 'examplectd.dat'

>>depth=examplectd(:,1); temp=examplectd(:,2); >>salinity=examplectd(:,3); oxygen=examplectd(:,4); >>fluro=examplectd(:,5);

The figure window is at the top of the heirachy! There are 62 parameters controlling the figure window. 2 commands used to change the settings: get and set

>>figure, plot(temp,-depth)

>>get(1) OR get(gcf) where gcf=get current figure.

The third parameter is Color = [0 0 0]

telling us that the color of the figure is black

>>get(gcf,’color’);

change the color by setting parameter

>>set(gcf,’color’,[0.2 0.2 0.2])

>>set(gcf,’name’,’ctd1 temp’); %%%puts name on fig

>>set(gcf,position’,[100 150 600 400]); %%can also use mouse!

axes also have properties – 90 but now have to get all of the axis properties:

>>get(gca)

If you want red instead of black axis window:

>>set(gca,’color’,[1 0 0]); %%%%%%%other parameters to adjust:

>>set(gca,’fontangle’,’italic’)

>>set(gca,’fontsize’,15)

>>set(gca,’linewidth’,2)

>>set(gca,’position’,[.2 .2 .6 .6])

>>set(gca,’xcolor’,[0 0 1])

>>set(gca,’xlim’,[1 24])

>>set(gca,’xtick’,[1:5:24])

>>set(gca,'xticklabel',['01C';'06C';'11C';'16C';'21C'])

can do many at the same time:

>> set(gca,'fontangle','italic','fontsize',15,'linewidth',2,'xgrid','on')

Adding text:>> title('ctd temperature plot')>> xlabel('temperature')>> ylabel('Depth (m)')

>> gtext('18C water') %%%%puts the text where you click on fig

also the functions: grid on and grid offhold on and hold off

>> load 'ADCP.txt' -ascii>> direction=ADCP(:,1);>> VelE=ADCP(:,2);>> VelN=ADCP(:,3);>> VelU=ADCP(:,4);

>> figure,plot(VelU)>> figure,plot(VelE)>> figure,plot(VelN)

other plotting options:

polar, rose and feather

in matlab the direction is needed in radians, and often the direction is given relative to north…… to find the direction in radians:

>>theta=(90-direction)*pi/180;

>> load('SST_IO')>> whos>> climoSST=squeeze(mean(SST));>> for mn=1:12;SSTanom(mn,:,:)=squeeze(SST(mn,:,:))-climoSST;end

%%%now we want to plot some contoured figures

>>temprange=[20:0.5:30] %%%defines the contours we’ll plot>>for mn=1:12

subplot(3,4,mn)contourf(lon,lat,squeeze(SST(mn,:,:)),temprange)caxis([20 30]); %%%%%%defines the limits of the colorbarend

>>colorbar

Or maybe we just want to plot a figure showing the annual mean and we want to interpolate

>> figure>> pcolor(lon,lat,climoSST);shading interp>> colorbar

%%%%%%%%%then we want to plot contourf lines on top for 25C>> hold on>> [cs,h]=contour(lon,lat,climoSST,[27 28 29],'w'); %%%[cs,h] is a way

%%of giving the contour lines a ‘handle’ in order to label them>>clabel(cs,’manual’);

%%now lets look at the anomalies>>temprange=[-10:0.2:10] %%%defines the contours we’ll plot>>for mn=1:12

subplot(3,4,mn)contourf(lon,lat,squeeze(SSTanom(mn,:,:)),temprange)caxis([-2 2]); %%%%%%defines the limits of the colorbarend

>>colorbar

look at times series over IO>> anom1=squeeze(nanmean(SSTanom,2)); %%%use nanmean as

%%there are NaN values as a landmask>> anomIO=squeeze(nanmean(anom1,2));>> figure,plot(anomIO)

%%%%%%Do some simple correlations, so create a similar time-series for the atlantic (a bit nonsensical but then you get the correlation programs!!!)

>> AO_anom=tan(anomIO);>> figure,plot(AO_anom), hold on,plot(anomIO,’:’)

y1=AO_anom;y2=anomIO; %%%%input variablesclear brol1 brol2 r1 r2 tau eodf r_95 prob t n r; %%%%%clear specific variables (if run this before)r=corrcoef(y1,y2); %%%%%%%calcluate correlation[c,lags]=xcorr(y1,y2,'coeff'); %%%%%calculate correlation at different time lags between dataif (abs(min(c))>=max(c)); %%%%find if the max correlation is positive or negativer=min(c),[x,y]=min(c);else; r=max(c),[x,y]=max(c);endn=length(y1);%%%%%%%%%%%%%%%%k=n/2;%%%%%%%%%%%%%%%%for i=1:k;brol1=corrcoef(y1(1:n-i),y1(i+1:n));brol2=corrcoef(y2(1:n-i),y2(i+1:n));r1(i)=brol1(1,2);r2(i)=brol2(1,2);end;

tau=[1+2*sum(r1.*r2)]; eodf=round(n/tau);r_95=1.96/sqrt(eodf-2) %%%%%%correlation at .95 confidencer_99=2.33/sqrt(eodf-2) %%%%%%correlation at .99 confidencet= abs(r/sqrt((1-r*r)/(eodf-2)));df=eodf-2;%prob_directional=tcdf(t,df)%prob_non_directional=1-(1-prob_directional)*2r %correlation, is it significant at the .95 or .99 level?lags(y) %%%% time lag (based on the timesteps of data set, if -ve then y2 leads y1

%%%%%%%help m_map – built in toolbox which allows you to plot on different projections (useful if looking at large areas). Also has built in topography and coastlines etc