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,

Slides:



Advertisements
Similar presentations
Introduction to MATLAB The language of Technical Computing.
Advertisements

M AT L AB Programming: scripts & functions. Scripts It is possible to achieve a lot simply by executing one command at a time on the command line (even.
Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
Loading Excel Double click the Excel icon on the desktop (if you have this) OR Click on Start All Programs Microsoft Office Microsoft Office Excel 2003.
EGR 106 – Week 2 – Arrays Definition, size, and terminology Construction methods Addressing and sub-arrays Some useful functions for arrays Character arrays.
Division Example 2x - 3y + 4z = 10 x + 6y - 3z = 4 -5x + y + 2z = 3 A*X = B where A = B = >> X = A\B X =
Introduction to MATLAB MECH 300H Spring Starting of MATLAB.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
FIRST COURSE Excel Lecture. XP 2 Introducing Excel Microsoft Office Excel 2007 (or Excel) is a computer program used to enter, analyze, and present quantitative.
Extending MATLAB Write your own scripts and/or functions Scripts and functions are plain text files with extension.m (m-files) To execute commands contained.
Mathcad Variable Names A string of characters (including numbers and some “special” characters (e.g. #, %, _, and a few more) Cannot start with a number.
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
Introduction to MATLAB
Objectives Understand what MATLAB is and why it is widely used in engineering and science Start the MATLAB program and solve simple problems in the command.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
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.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
GUI development with Matlab: GUI Front Panel Components 1 GUI front panel components In this section, we will look at -GUI front panel components -Programming.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
MATLAB – PT1 The purpose of this workshop is to get you started and to have fun with MATLAB! Let’s talk a little and decide on what we will be covering.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Files Tutor: You will need ….
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
Digital Image Processing Introduction to MATLAB. Background on MATLAB (Definition) MATLAB is a high-performance language for technical computing. The.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Manipulating MATLAB Vector, Matrices 1. Variables and Arrays What are variables? You name the variables (as the programmer) and assign them numerical.
An Introduction to Programming in Matlab Emily Blumenthal
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
Getting started with Matlab: Outline
Reading and Writing Image Files
Linear Algebra Review.
Release Numbers MATLAB is updated regularly
Prof. Mark Glauser Created by: David Marr
Examples, examples: Outline
Ch3 Graphics Overview of Plotting Editing Plots
Computer Fundamentals
Basic operations in Matlab
Outline Matlab tutorial How to start and exit Matlab Matlab basics.
INTRODUCTION TO BASIC MATLAB
MATLAB DENC 2533 ECADD LAB 9.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
StatLab Matlab Workshop
MATH 493 Introduction to MATLAB
Use of Mathematics using Technology (Maltlab)
MATLAB Tutorial Dr. David W. Graham.
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Lecture 2 Introduction to MATLAB
MatLab – 2D Plots 2 MATLAB has many built-in functions and commands to create various types of plots. Instructor notes: We start with an example of some.
MATLAB How to use (using M-files)
Matlab Training Session 5: Importing Data
funCTIONs and Data Import/Export
INTRODUCTION TO MATLAB
Note on Indexing of Array Elements
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Experiment No. (1) - an introduction to MATLAB
MATLAB Introduction MATLAB can be thought of as a powerful graphing calculator but with a lot more buttons! It is also a programming language, commands.
Announcements P3 due today
Matlab Basics Tutorial
Chapter 2 MATLAB Environment
Presentation transcript:

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

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

Change visible details Current directory Command window

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’

Matlab files are saved as .m files

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)

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

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)

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

>>gheko=[1,2,3;4,5,6;7,8,9] >>whos >>whos dog

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)

Circle Area = π • r² = ¼ • π • d² >> mean(X,1) ans = 2.2000 5.0000 4.2000 4.6000 5.0000 >> 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

What about nansum and nanmean

Creating matrices: >>A=3.14 >>B=[1 9 3 5 2 4 6 8 3 9] 1x10 To make a more general matrix, separate by; >>C=[1 2 3 4; 3 4 5 6; 8 6 4 2] 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?

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(:,[2 1 3 4]) interchanges the first and second column. Or to remove 3rd column >>C1=C(:,[1:2 4]);

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)

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!!!!

>>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)………

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’

Calculate the square root of x >>y1=x^0.5 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,’:’)

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:15 counter=counter+1 if i<12 a(counter)=i*2; elseif i==12 a(counter)=i; elseif i>12 a(counter)=i*3; end

>>while i>5; >> a(i)=i*2; >> i=i-1; >>end

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 646969323 (i.e. find the sequence of prime numbers resulting in this number when multiplied together) 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. 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?

Code 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 hypothetical data……. Answer the following questions >>data=sin(X/1000).*cos(Y/100).*tanh(Z/2000);

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 = Janvalue1999 - Janmean(1990-1999); d) Plot the July anomaly for 1995 (help contour)

Answer Codes >> size(data) ans = 10 19 120 >> min(data(:)) 10 19 120 >> min(data(:)) >> max(data(:)) 0.26694353105108 >> mean(data(:)) 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); >> for yr=1:10 >> Mn_anom(:,:,m,yr)=squeeze(data2(:,:,m,yr))-squeeze(mn_climo(:,:,m)); >> end

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);

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 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

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\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

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)

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

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 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’,[.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 off hold on and hold off

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;

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

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,[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 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)

%%%%%%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,’:’)

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

%%%%%%%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