Beginning Programming in MATLAB
Beginning Programming in MATLAB
MATLAB
MAM1043H
How do we do this?
Create a new m-file: (File\New\M-File)
MATLAB script editor opens.
The function
name: f()
ff
y=f(x)
The actual calculation is performed inside
the black box...
Save m-file as
f.m
The function
name: f()
The input
variable(s) to the
function: x
Function m-files
Repeating Statements
Often, we want to repeat some operation a
number of times.
Examples you are already familiar with
Series: S = 1+2+3+...N
Factorial: F = 1x2x3x...xN
Taylor Series: sin(x) = x+x3/3! + ...
Newton's method: xn+1=xn -f(xn)/f'(xn)
end;
Ending value
The statements to be
repeated
example02.m
example02.m
forn=1:5
forn=1:5
y=n^2;
y=n^2;
disp(y);
disp(y);
end;
end;
Need to keep adding n2
to the sum, stored in S
Calculates 5!
example03.m
example03.m
example04.m
example04.m
N=5;
N=5;
S=0;
S=0;
N=5;
N=5;
F=1;
F=1;
forn=1:N
forn=1:N
S=S+n^2;
S=S+n^2;
end;
end;
forn=1:N
forn=1:N
F=F*n;
F=F*n;
end;
end;
disp('SUM=');
disp('SUM=');
disp(S)
disp(S)
fk = fk-1 + fk-2
Still to come
How can we solve linear system of
equations?
Making decisions and logical operations.
Numerically solving differential equations.