You are on page 1of 9

MATLAB LECTURE 9

Programming in MATLAB

FOR LOOP
N = input(Enter a positive integer:);
fact = 1;
for k = 1:N
fact = fact * k;
end
fprintf(The factorial of %4.0f is %10.0f \n, N, fact);

EXAMPLE (FOR LOOP)


Lets deal with a geometric series G = pk where
p = 0.99 and k = 0 to 1000
Calculate each term in the series (before
summation) geomSeries = pk
Calculate the value of the infinite series
G = pk = 1 /(1-p) = 1/(1-.99) = 100

plot geomSeries versus k

With for loop


G = 0;
p = 0.99;
for k = 0:1000
geomSeries = p^k ;
G = G + geomSeries ;
plot(k, geomSeries, 'o'); hold on;
end
disp(G);

Without for loop


p = 0.99;
k = 0:1000;
geomSeries = p .^k
plot(k, geomSeries);
G = sum(geomSeries);
fprintf('Sum of geometric Series is %f \n', G);

NESTED FOR LOOP: ADD TWO


MATRICES
% matix dimension should be the same for both
A = [ 1 4 8; 5 3 -1 ; 0 7 9; 4 3 2] ; %4 rows, 3 columns
B = [2 3 4; 5 6 7; 8 9 1; 0 2 3] ;
% i is the row number , j = column number
for i = 1:4
for j = 1:3
C(i,j) = A(i,j) + B(i,j) ;
end
end
%display C
disp(C);
% matix dimension should be the same for both
A = [ 1 4 8; 5 3 -1 ; 0 7 9; 4 3 2] %4 rows, 3 columns
B = [2 3 4; 5 6 7; 8 9 1; 0 2 3]
C =A+ B

Without for loop

FOR LOOP WITH IF STATEMENT


CONSTRUCT AN IDENTITY MATRIX
%Identity matrix of size 3x3
for i = 1:3
for j = 1:3
if i == j
ID(i,j) = 1;
else
ID(i,j) = 0;
end
end
end
disp(ID)

IMPORT/EXPORT DATA
You can open any file from MATLAB by using
fopen() command
Use help fopen to find more
fid = fopen(filename, r) open file for reading
fid = fopen(filename, w) open file for writing
fclose(fid) Close the file.
fprintf() to write data on the file
fscanf() to read data from the file

FOPEN()
fid=fopen('C:\Users\student\D
ocuments\MATLAB\Example.t
xt', 'w');

for i = 1:20
new = [i, 10*rand(1,2)];
fprintf(fid, '%f %f %f\n',
new);
end
fclose(fid);

fid = fopen('Example.txt , 'r');


data = fscanf(fid,'%f %f %f',
[3,inf])';
% '3' for three columns, 'inf' means
up to the last column

fclose(fid);
% data contains 3 columns and 20
rows

plot(data(:,1), data(:,2));