Introduction to MATLAB

From SEG Wiki
Jump to navigation Jump to search
ADVERTISEMENT

MATLAB is the programming language that will be used to perform calculations for the following Seismology labs. In this session the basics of MATLAB is presented. For a general overview you can check the Getting started with MATLAB video

MATLAB environment

The figure below shows the default configuration of MATLAB once it is launched.

Matlab environment copy.png

Description of the numbering on the figure above

1.This folder icon with the downward green arrow is used to map the working folder.
To keep organized your code create a working folder before beginning to work with MATLAB and map it by clicking on this icon

2. This pane displays the items in your current folder (working folder)

3. This pane displays the variables stored in the working memory.
This is a temporary memory.

4. This is the command window. This is the window where MATLAB commands are typed

Help Documentation

There are several ways to get help in MATLAB. Two common ways are to use the Search Documentation box or the " ? " icon, both placed at the top right of the MATLAB window.
Other ways to get help are described in ways to get help in MATLAB

Working with scalar variables

Creating scalar variables

  • Create a variable named awhose value is .

In the command window type: a = pi then hit enter.
You should see something like the following in the command window:

>> a=pi

a=
    3.1416
  • Check your workspace. You should be able to see the name of the variable and its value. Double click on it and find out what happens.
  • To perform basic operations use: "+" " -" for addition/substraction, "*" "/" for multiplication/divison and

^ to raise to the power.

  • Type the following commands: What are the values of b and d ?
 b=log(3)^2
 d=sin(a/2)+a*b
  • In the previous commands, two built in functions log() "natural logarithm" and sin() "sine" were used. Built-in functions are all in lower case and the argument is typed within the parenthesis.
  • Questions:

- Re-type the previous commands but this time add a semicolon  ; before hitting enter. What happens?.
- What happens if you use the up and down arrows in a new line in the command window?
- Type clc. What happens in the command window?
- Type clear. What happens with the variables in the workspace?
- Type b. What happens?

Saving variables

  • The variables created in the command window are temporal, once you clear them, they are gone.
  • Create again variables a , b and d
  • You can save each variable by right clicking on them in the workspace. You can also save all the variables of the workspace at once by clicking on the down arrow at the top right of the workspace pane.

The files are visible in the current folder pane and they have a .mat extension.

  • Type again the clear command in the command window
  • Retrieve the variables by double clickling on the .mat files just created. Type again b in the command window.

Working with vectors

Creating vectors

  • Create the following row vectors: x={1,2,3} and s={0,2,4,...,18,20}

- One way to create a vector is by typing its elements, specially when it has few elements.

x=[1,2,3];

Comma to separate elements is optional, a blank space will do as well

- Another way to create a vector is by defining its range: initial_value:step:final_value . Vector s is created in this way.

s=0:2:20;
  • One can also know the number of elements of s by typing:
length(s)

Elements of a vector

  • To take element (s) from vectors, we use parenthesis specifying the position of such element(s).

- Example 1 : Take the second element of x and the last element of s

x2=x(2);
slast=s(end);

- Example 2 : Take the first 10 elements of s.

sten=s(1:10);
  • Questions

- How would you create the following vector: t= {0, 0.01, 0.02,..., 1 }.
- Create vector t2 formed by elements of t from positions 10 to 20.

Vector operations

  • Create vectors u={0,1,2} and v={15,25,35} and perform the following operations.
c=3*v+u;   
e=dot (v,u);
r1=cross(u,v);
r2=cross (v,u);
n=norm(v);
  • Element by element operation between vectors. For this type of operation the vectors must have the same number of elements. For this case both u and v have 3 elements each.

- Find out the results of the following commands. Note that in the commands a . preceds the operation symbol *, ^, /

f=u.*v;
g=u.^2;
h=1./u;

2-D plots and .m files

  • A script is a MATLAB file where code is saved, so there is no need to write the commands in the command window each time. You can check the writing a MATLAB program video for more information.
  • To create a .m file, go to HOME and click "New Script". Save it as matlabplots. You should be able to see this file in the Current folder pane

- Type the following commands inside the file you just created to produce a 2-D plot.
Note: What is written after the symbol % is a comment and it is not executed.

t=0:0.01:1;   % creates  vector t with elements from 0 to 1 in intervals of 0.01
y=sin (3*pi*t);   % creates vector y 
z=cos (3*pi*t);   % creates  vector z 

%plots
close all;  % close all open windows
figure;  % opens a new figure window
plot(t,y);  % plots t in the horizontal axis and y in the vertical
title ('y=sin(3*pi*t)');   % plot title
xlabel ('time (s)');  % adds x label 
ylabel ('amplitude (m)');  % adds y label

figure;  % opens a new figure window
plot(t,z);  % plots t in the horizontal axis and y in the vertical
title ('z=cos(3*pi*t)');  % plot title
xlabel ('time (s)');  % adds x label 
ylabel ('amplitude (m)');  % adds y label

- To run the script, type in the command window the name of the script: matlabplots. You can save your plots by clicking on File -> Save as on the figure window. Choose a jpeg format to have a portable figure.

  • The script above plots each curve in a different window. To plot both curves in the same window you can add the commands below to your script. The commands below show 2 ways to plot both curves in a single window:

- Using hold on and hold off commands

figure; 
plot(t,y);
% to add plots in the same window we can use hold on and hold of commands
hold on;
plot (t,z); % try:  plot (t,z, '--') and see what happens
hold off;
legend ('sin (3 pi t)','cos (3 pi t)');  % adds a legend
xlabel ('time (s)');
ylabel ('amplitude (m)');

- The other way to produce more than one plot in the same window is to add more arguments to the command plot:

figure;
plot (t,y,t,z); % try:  plot (t,y,t,z,'--')
legend ('sin (3 pi t)','cos (3 pi t)'); % adds  a legend
xlabel ('time (s)');
ylabel ('amplitude (m)');

Working with matrices

Creating a matrix

  • Create the following matrix by typing in the command window:
a=[2 4 6;8 10 12];

- Note that a semicolon ; indicates a new row

  • Taking elements of a matrix

- Take an element of a from row 2 and column 3 and assign its value to b:

b=a(2,3);

- Create vector c by taking all rows of column 1 of a:

c=a(:,1);
  • How would you create vector c by taking all columns of row 2 of a?

Eigenvalues and Eigenvectors

  • Create the following matrix:
  • Calculate the eigenvalues and eigenvectors of matrix stress by using the eig command :
[v,d] = eig (stress);

- Note that the colums of v are the 3 eigenvectors: v1, v2, v3 and the diagonal of d are the 3 corresponding eignevalues: d1,d2,d3

  • Questions:

- How would you take the first eigenvector from v and assign it tov1?
- How would you take the first eigenvalue from d and assign it to d1?

Creating functions

  • Creating a customized function is very similar to creating a script.You can check the writing a MATLAB program video for more information. As an example we will create a function that calculates the tractions along the principal directions.
    Remember: ti = stress. ni = di* vi

i) Create a .m file named tractions
ii) In the editor declare the function tractions as follows

function  [t1,t2,t3] = tractions ()

end

Important notes:
- To create a function use the key word function and the key word end
- Optional: Inside [ ]provide the output of the function. In this case: t1,t2,t3.
- After the equal sign provide the name of the function. In this case tractions.
- The name of the first function has to match the name of the .m file.
- Inside () you can provide parameters for the function. In this case there is none.

iii) Complete the body of the function. Use the code below as a guide:

function  [t1,t2,t3]=tractions()
clear ;
stress = [ 10 50 30; 50 20 40; 30 40 60]; % declare the stress matrix
[v,d] =eig(stress); % calculate the eigenvectors and eigenvalues
t1 = v(:,1)*d(1,1); % calculate the first traction
t2 =		% complete this line
t3 =		% complete this line

end

iv) To run the function then type in the command window:

[t1,t2,t3]= tractions();
  • We can also call from the tractions function several other functions. In this case we will create a plotTractions function in the same .m file. This function plots the calculated tractions

i) In the editor type:

function plotTractions (t1,t2,t3)
 
close all;
hold on ; % hold on and hold off is used to plot on the same window
 
quiver3(0,0,0,t1(1),t1(2),t1(3)); 
quiver3(0,0,0,t2(1),t2(2),t2(3));
quiver3(0,0,0,t3(1),t3(2),t3(3));
xlabel ('x')
ylabel ('y')
zlabel ('z')

hold off;
 
end

ii) To call the plotTractionsfunction, add the following line in the tractionsfunction before the keyword end.

plotTractions (t1,t2,t3) %add this line in the tractions function

ii) Run again the tractions function as previously.

Loops and Conditionals

  • Loops are repetitive statements that are executed until certain condition is met. In this tutorial we will use the for loop. Another type of loop is the while loop.
  • Conditionals allow to select which piece of code to execute at run time. For that we will use an if statement.

Example: Create a vector r1 with 100 elements of random numbers between 1 and 200. Then, extract those elements that are less than or equal to 80 and assign them to a second vectorr2. Finally, create a stem plot with the elements of r2.

i) First create a .m file named random.

ii) Type the following in the editor.

function r2=random()
% creating vector r1 with 100 random numbers between 1 and 200
r1=200*rand(100,1); 
 
% creating a vector of zeros of the same length as r1
r2 = zeros (1,length(r1));
 
% this variable will help to add elements to r2
count=0;
 
% for loop: "n" is a variable which takes the value of 1 at the beginning
% then it increments in steps of 1. The loop ends when n= length(r1)

for n=1:length(r1)
% what is inside the for loop is executed for every value that n takes
      
    if r1(n) <=80 % if this condition is met then the code inside is executed if not it is skipped
        count=count+1; % the counter increments
        r2(count) = r1(n); % the n-th element  of r1 is assigned to r2     
    end % this is the end for the conditional
       
end % this end for the "for loop"
 
% delete trailing zeros in r2 
 r2(count+1:end)=[];
 
 % plotting
close all;
figure;
stem (r2)
 
end

iii) Run the function by typing on the command window:

r2 = random()