Download presentation
Presentation is loading. Please wait.
Published byAlexander Green Modified over 6 years ago
1
OTGA UEM RTC Introdução ao Matlab: introdução de dados, batimetria, linhas de contorno, traçar diagramas e perfis 24 Janeiro 2017 Fialho Nehama, UEM-ESCMC, Quelimane Moçambique With the support of the Government of Flanders, Belgium
2
Matlab – short for matrix library (matrices are the building blocks of Matlab. Matrices (or arrays) can be of all dimensions: Simple elements – 1x1 matrices, vectors – 1xN matrices, mulitple dimensional matrices (MxNx…). Matlab has many built in functions and hundreds of other functions in ‘toolboxes’. For example – the statistics toolbox, containing functions for calculating correlations, mean values, variances…….. There are many matlab tutorials you can download on the internet, This is a combination of ones written by Tore Furevik and Seb Swart and Bjorn Backeberg
5
Change visible details
Current directory Command window
6
Arrows on key board are useful shortcuts in Matlab
Arrows on key board are useful shortcuts in Matlab. They are useful for flicking through your recent commands. The up arrow displays the last command – sin(1). Pressing it twice will bring up the ‘why’ command. The command can be edited by pressing the left arrow once and deleting 1 and putting 2. Can also put the first few letters of a command and press the tab button Or a few letters of a previous command and the up arrow will fill it in. Matlab is CASE SENSITIVE….try SIN(2) If you get into a struggle – ‘ctrl c’
7
Matlab files are saved as .m files
9
Matlab file formats: .m (programs) .mat (saved data) .fig (saved figures Can specify to save figs as anything else, eg .jpeg, .tiff…… Can import and export data in any file (eg netcdf)
11
At the >> prompt, one can directly enter commands.
As an example, this is one way to compute 2+2: >> a = 2 a = 2 >> b = 2 b = 2 >> c = a + b c = 4 It is often annoying to have Matlab always print out the value of each variable. To avoid this, put a semicolon after the commands: >> a = 2; >> b = 2; >> c = a + b; >> c Only the final line produces output. Semicolons can also be used to string together more than one command on the same line: >> a = 2; b = 2; c = a + b; c c = 4
12
Of course Matlab will also allow more complicated operations:
>> quad1 = (-b + sqrt(b^2 - 4*a*c)) / (2*a) quad1 = 4 quad2 = (-b - sqrt(b^2 - 4*a*c)) / (2*a)
14
The lookfor command is also very useful
The lookfor command is also very useful. It searches through matlab functions to look for whether matlab has a function for the desired purpose. Try >> lookfor mean It only looks through the first line, to search the entire function: >>lookfor mean –all Or if you have an idea already… >>which mean
18
>>gheko=[1,2,3;4,5,6;7,8,9] >>whos >>whos dog
19
Make the following matrix:
What is the mean value of each column and row? What is the minimum value of each column What is the mean, minimum and standard value and variance of the entire matrix Type mean=2 and try and calculate the mean again? How can you get rid of this? In Matlab there are several predefined constants (as there are functions). These include pi, i and j. The first being the ratio between the circumference and diameter of a circle and the latter 2 are both the imaginary unit vector What is the area and volume of a sphere with radius 6371km What is exp(i*pi)? Calculate (1+i)*4 and sin(2)+i*sinh(2i)
20
Circle Area = π • r² = ¼ • π • d²
>> mean(X,1) ans = >> mean(X,2) ans = 3.2000 4.6000 3.8000 4.0000 5.4000 >> min(X,[],2) >>mean(X(:)) Circle Area = π • r² = ¼ • π • d² Sphere Volume = 4/3 • π • r³ = ( π •d³)/6 Euler's formula: e^(i pi) = -1
21
What about nansum and nanmean
23
Creating matrices: >>A=3.14 >>B=[ ] 1x10 To make a more general matrix, separate by; >>C=[ ; ; ] To extract elements: C(1,1) C(2,3) Matlab interprets a single index number as a row number. If the index number is larger than the number of rows, it will start over in the next column. C(5) becomes 4 and C(8) becomes 5. Rand(2,3) Ones(2,5) Magic(5) – what is special about this?
24
Colons!!!! >a=1:10 >>a=1:2:10; >>b=9:-3:-9; >>c=0:0.2:2; >>d=0:pi/6:2*pi; >>C=[1:4;3:6;8:-2:2]; >>C(1:2,3) >>C(3,2:4) >>C(:,3:4) Change sequence: >>D=C(:,[ ]) interchanges the first and second column. Or to remove 3rd column >>C1=C(:,[1:2 4]);
25
Or join matrices: >>C2=[C C C1;C1 C C]; Or else C(3:end); get all elements from 3rd to last (if we don’t know length) Matrix dimensions >>x=rand(2,3,7,5); >>size(x) >>prod(size(x)); >>length(x) >>max(size(x)); Change the matrix dimensions without altering the sequence: >>y=reshape(x,2,3,35); size(y); >>z=reshape(x,prod(size(x)),1); size(z)
26
Reshape doesn’t change elements
Reshape doesn’t change elements. Useful if eg have a matrix with values for every month over a period of years and we want the mean value for just January >>[val,ind]=max(x(:)) %find the max value of the matrix and it’s position in the sequence (between 1 and 210). Although it is usually more helpful to know the position in the matrix >>[a,b,c,d]=ind2sub(ind,size(x)) %find the max value in x(a,b,c,d) we need 4 indices since we have a 4D matrix Check with help function >>[a,b,c,d]=ind2sub(size(x),ind) Testran program!!!!! Linefit program!!!!
28
>>x=[1:5:30 NaN 20:-2:4 Inf];
>>I=isfinite(x) %returns a vector where the elements of x are finite numbers and 0 where they are not….find the indices to all elements of value 1 for I >>J=find(I) %elements 7 and 17 are omitted to remove them >>x=x(J) Alternately >>x=x(isfinite(x)) Replace all numbers >15 with 0 >> i=find(x>15); >> x(i)=0 >>x(find(x>15))=0; OR >>x(isprime(x))=x(isprime(x)).^2 %squares all prime numbers >>y=x(find(x>=10) %create a new vector with all numbers >10 isnumeric and ischar checks if a variable is a number or character A=‘word’ and B=100; isnumeric(A)………
29
Generate a sequence of numbers from 0 to 10 with step length 0.01
Calculate the sin and cosine to all the numbers and visualize with plot >>x=0:0.01:10; >>y1=sin(x); >>y2=cos(x); plot(x,y1,x,y2,’--’) %%%%%%%plot different lines plot(x,y1,’r’,x,y2,’k’) %%%%%change colour of line; %%%%%%%%%%%%%plot lines with different colours and styles plot(x,y1,'w') hold on plot(x,y2,'r','linestyle','--') get(gcf) %%gives you all of the figure ‘handles’
30
Calculate the square root of x
>>y1=x^ or >>y1=sqrt(x) Have to include a dot in order to multiply or divide element by element, x.^0.5 >>y1=x.^0.5; y2=x.^1.5; y3=x.^2; >>plot(x,y1,x,y2,’—’,x,y3,’:’)
31
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);
33
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:15 counter=counter+1 if i< a(counter)=i*2; elseif i==12 a(counter)=i; elseif i>12 a(counter)=i*3; end
34
>>while i>5; >> a(i)=i*2; >> i=i-1; >>end
35
Tasks Create a vector X with values from 0 to 100 at intervals of 0.1 What is the 20th prime number in X How many prime numbers are less than 1million Factorize (i.e. find the sequence of prime numbers resulting in this number when multiplied together) Create the vector X=[ ] 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. Which sentence is represented by X? What is the ascii code for ‘enter’ Using findstr what is the position of r in the above text?
36
Code X=[0:0.1:100]; t=primes(100); t(20) t2=primes( ); size(t2) f=factor( ); x=[ ]; s=char(x); double('enter'); findstr(x,'r')
37
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 with steps of 1/12: >>[X,Y,Z]=meshgrid(0:20:360,-90:20:90,1990:1/12: ); Generate the hypothetical data……. Answer the following questions >>data=sin(X/1000).*cos(Y/100).*tanh(Z/2000);
38
a) What is the size of the matrix data
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 longitude and latitude 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 = Janvalue Janmean( ); d) Plot the July anomaly for 1995 (help contour)
39
Answer Codes >> size(data) ans = 10 19 120 >> min(data(:))
>> min(data(:)) >> max(data(:)) >> mean(data(:)) >>[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); >> for yr=1:10 >> Mn_anom(:,:,m,yr)=squeeze(data2(:,:,m,yr))-squeeze(mn_climo(:,:,m)); >> end
40
Reading ascii data w/o header
Example ctd >> clear all >> load examplectd.dat Whos – examplectd in workspace which is 2138x5 Ignores 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);
41
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
42
Ascii-data with boring header
Use 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
43
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.
44
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.
45
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));
46
saving ascii-data The opposite function of load is save
>>load examplectd.dat; >>save 'C:\Documents and Settings\fialho\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
47
To separate data with column usinf fprintf…
load 'examplectd.dat' >> fid=fopen('ctd3.asc','wt') >> fprintf(fid,'%4d %6.3f %6.3f %6.2f %5.3f\n',examplectd'); >> fclose(fid)
48
Plotting the CTD data from examplectd.dat
>>load 'examplectd.dat' >> depth =examplectd(:,1); >> temp =examplectd(:,2); >> salinity=examplectd(:,3); >> oxygen=examplectd(:,4); >> fluoro =examplectd(:,5); The figure window is at the top of the heirarchy! 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. % lists figure parameters
49
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’,[ ]) >>set(gcf,’name’,’ctd1 temp’); %%%puts name on fig >>set(gcf,position’,[ ]); %%can also use mouse!
50
axes that appear in the figure 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’,[ ]) >>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'])
52
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 off hold on and hold off
53
Plotting the CurrentMeter data from adcp.txt
>> 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 available: 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;
54
Plotting the SST data from SST_IO.mat
>> 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 colorbar >>end >>colorbar
55
Or maybe we just want to plot a figure showing the annual mean and we want to interpolate
>> 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,[ ],'w'); %%%[cs,h] is a way %%of giving the contour lines a ‘handle’ in order to label them >>clabel(cs,’manual’);
56
%%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 colorbar end >>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)
57
%%%%%%Do some simple correlations, so create a similar time-series this is just a nonsensical timeseries we will create and call atlantic ocean. Obviously this is just a timeseries we create from the indian ocean data but it saves downloading further data! (a bit nonsensical but then you get the correlation programs!!!) >> AO_anom=tan(anomIO); >> figure,plot(AO_anom), hold on,plot(anomIO,’:’)
58
y1=AO_anom;y2=anomIO; %%%%input variables
clear 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 data if (abs(min(c))>=max(c)); %%%%find if the max correlation is positive or negative r=min(c),[x,y]=min(c); else; r=max(c),[x,y]=max(c); end n=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 confidence r_99=2.33/sqrt(eodf-2) %%%%%%correlation at .99 confidence t= abs(r/sqrt((1-r*r)/(eodf-2))); df=eodf-2; %prob_directional=tcdf(t,df) %prob_non_directional=1-(1-prob_directional)*2 r %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
59
%%%%%%%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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.