INTRODUCTION TO MATLAB


 

>>b=0:0.2:1;

 

% b=[0 0.2 0.4 0.6 0.8 1]

>>A=[1 2 3; 4 5 6; 7 8 9];

‘;’ : end of row indicator

A is a 3x3 matrix, A(1,1)=1, A(1,3)=3, A(3,2)=8, etc.

>>r=[10 11 12];

>>A=[A;r];

A is now a 4x3 matrix, A(4,1)=10, etc.

+, -

:

matrix addition and subtraction

*

:

matrix multiplication

^

:

matrix power, A^3=A*A*A

‘

:

matrix transpose

.*

:

element by element multiplication

./

:

element by element division

by default

>>z=9+7*i;

 

% define a complex number, real(z)=9, imag(z)=7

>>for i=1:10,

 

% for loop

x(i)=i;

 

 

end;

 

% x=[1 2 3 4 5 6 7 8 9 10]

>>

>>i=1;

 

% while loop

 

 

 

>>while i<=10,

x(i)=i;

i=i+1;

end;

% x=[1 2 3 4 5 6 7 8 9 10]

>>if (x(1)= =1)

 

% if statement

x=x*2;

else

x=x/2;

end;

 

% x=[2 4 6 8 10 12 14 16 18 20]

&

:

logical and

|

:

logical or

~

:

not

= =

:

equal

~=

:

not equal

sin(x), cos(x), sqrt(x), length(x), log(x), …

example:

% a function that computes the mean and standard deviation

% of the elements in a vector x

% function name is stat

% must be saved using the function name with extension .m,

% i.e. stat.m

function [mean,stdev] = stat(x)

L=length(x);

mean=sum(x)/L;

stdev=sqrt(sum(x.^2)/L-mean^2);

a text file that contains MATLAB commands, must be saved with extension ".m"

key in filename without extension in MATLAB executes the commands in the scrip file

example:

% a script file that calls function stat

% script file saved as test.m

x=41:50;

 

% define data

time=1:10;

plot(time,x);

 

% plot the data vector x

[mean,stdev] = stat(x);

 

% call function stat, returned

 

 

% values in mean and stdev

fprintf('mean: %3.2f\n',mean);

fprintf('standard deviation: %2.4f\n',stdev);

>>test

 

% run the commands in test.m

>>mean: 45.50

>>standard deviation: 2.8722

>>save abc.mat

 

% save the whole workspace

>>load abc

 

% load entire workspace

>>save xy.dat x y -ascii

 

% save variables x and y in xy.dat

>>load xy.dat

 

% load the data stored in the file

 

% result in vector xy

>>help zeros

 

% explain how ‘zeros’ works