You are on page 1of 5
 SOME MATLAB CONCEPTS Maarten van Walstijn PBASS MATLAB CONCEPTS 1 SCRIPTING , EDITING, EXECUTING File.m is a ‘Matlab script’: command 1 Contains a series of commands (command lines) that execute a particular set of instructions. command 2 …. …. Can be created & edited with the Matlab editor. Go to within working directory Store in ‘work’ folder Execute by typing filename Into Matlab comand-line >> >> >> file PBASS MATLAB CONCEPTS 2
Indexing
Matlab uses matrices and vectors a lot. In order to make good use
of them, one needs to understand how to ‘index’ them. That is, how
to ‘call’ specific vector elements and how to store values into
specific vector elements.
calling
storing
>> y = 1:5
>> y = zeros(1,5)
y
=
y
=
1
2
3
4
5
0
0
0
0
0
>> ym = y(2:4)
>> y(3:5)= [2 1 3]
ym =
y
=
2
3
4
0
0
2
1
3
3
PBASS
MATLAB CONCEPTS
Vectorisation (1)
Matlab allows to perform the same computational operation
for a series of numbers within one command. For example:
>>
>> x = 1:5;
>>
>> y = 5:-1:1
>>
>> z = x + y
z
=
6
6
6
6
6
>>
4
PBASS
MATLAB CONCEPTS
 Vectorisation (2) When using vectorised operations, one must in some cases use A period ‘.’ before the normal operation. For example, >> z = x.*y z = 5 8 9 8 5 >> z = x./y z = 0.2000 0.5000 1.0000 2.0000 5.0000 >> PBASS MATLAB CONCEPTS 5 ‘For-Loops’ A series of commands of the same format is usually code with a so-called ‘for-loop’. For example, we could have done the previous exercise as follows: N = 5; x = 1:N; y = N:-1:1; z = zeros(1,N); % creating a new vector to store the result in %%% for-loop %%% for n=1:N z(n) = x(n) + y(n); end Often it is not efficient to use a fot-loop, as it requires more code and runs slower!. One case in which we always need a fo-loop is when the elements of the result-vector need to be computed recursively. PBASS MATLAB CONCEPTS 6
SCRIPT STUCTRURE
Most computational task are based on a certain order. In the previous
examples: I n order to compute z , one must first ‘declare’ or ‘initialise’
what x and y are.
%%%% example file %%%%
Hence very often scripts tend to be
structured as follows:
%%% initialisations %%%
x = 1:5;
y
= 5:-1:1;
Initialisations
%%% calculations %%%
z1 = x + y;
Calculations
z2 = x.*y;
%%% plotting %%%
figure(1);
plot(z1);
Displays
figure(2);
plot(z2);
7
PBASS
MATLAB CONCEPTS
SUBROUTINES
Subroutines can be very useful when using the same operation
more than one time. In Matlab one can do this by starting a
script with ‘function’:
%%%% example file %%%%
Subroutine scripted as:
%%% initialisations %%%
x = 1:5;
y = 5:-1:1;
z1 = x + y;
z2 = x.*y;
%%% calculations %%%