Professional Documents
Culture Documents
<file.m>
File.m is a ‘Matlab script’:
Contains a series of commands
command 1
command 2 (command lines) that execute a particular
…. set of instructions.
….
Can be created & edited with the Matlab
editor.
>>
>>
>> file
1
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 3 4 0 0 2 1 3
Vectorisation (1)
>>
>> x = 1:5;
>>
>> y = 5:-1:1
>>
>> z = x + y
z=
6 6 6 6 6
>>
2
Vectorisation (2)
>> z = x.*y
z=
5 8 9 8 5
>> z = x./y
z=
>>
‘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
3
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 %%% initialisations %%%
structured as follows: x = 1:5;
y = 5:-1:1;
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;
function[z1,z2] = AddAndMult(x,y)
%%% calculations %%%
z1 = x + y;
[z1,z2] = AddAndMult(x,y);
z2 = x.*y;
%%% plotting %%%
figure(1);
plot(z1);
figure(2);
And saved as ‘AddAndMult.m’ plot(z2);
4
SOME PLOTTING TRICKS (1)
plot(x1,y1,’b-’,x2,y2,’ro--’)
Plots two sets of x-y data: the first with a blue solid line, and the second
with a dashed red line plus a red circle at each data point. The same can
also be realised with:
plot(x1,y1,’b-’)
hold on;
plot(x2,y2,’ro--’)
hold off;
axis off; -> makes all axes disappear (data only display)
axis([xmin xmax ymin ymax]); -> sets the ‘view’ to specified x an y ranges.