Computer Programming With MATLAB
Computer Programming With MATLAB
by
Repeat for n = 1 to 5
Add n to total
Print total
Set total to 0
Set n to 1
Execute Add n to total (total equals 1)
Set total to 0
Set n to 2
Execute Add n to total (total equals 3)
Set n to 3 Repeat for n = 1 to 5
Execute Add n to total (total equals 6)
Add n to total
Set n to 4
Execute Add n to total (total equals 10)
Set n to 5
Print total
Execute Add n to total (total equals 15)
Print total
MATLAB implementation using a for-loop:
total = 0;
for n = 1:5
total = total + n;
end
fprintf('total equals %d\n',total);
total = 0;
for n = 1:5 control statement
loop total = total + n; body
end
fprintf('total equals %d\n',total);
Here is another example:
list = rand(1,5); % assigns a row vector of random numbers
for x = list
if x > 0.5
fprintf('Random number %f is large.\n',x)
else
fprintf('Random number %f is small.\n',x)
end
end
for x = rand(1,5)
if x > 0.5
fprintf('Random number %f is large.\n',x)
else
fprintf('Random number %f is small.\n',x)
end
end
The values assigned to the loop index do not
have to be
◦ integers,
◦ regularly spaced, or
◦ assigned in increasing order,
In fact, they do not have to be scalars either:
◦ The loop index will be assigned the columns of the array
Any other control construct can be used in the
body of the for-loop
◦ if-statements
◦ other loops
◦ etc.
for-loops work well when we know the
number of necessary iterations before
entering the loop
Consider this problem:
◦ Starting from 1, how many consecutive positive
integers do we need to add together to exceed 50?
◦ The only way to solve this with a for-loop is to guess
a large enough number for the number of iterations
and then use a break statement.
◦ There is a better solution: a while-loop!
function [n total] = possum(limit)
total = 0;
n = 0;
while total <= limit
n = n + 1;
total = total + n;
end
fprintf('sum: %d count: %d\n', total, n);
function [n total] = possum(limit)
total = 0;
n = 0;
while total <= limit
n = n + 1;
total = total + n;
end
fprintf('sum: %d count: %d\n', total, n);
>> possum(50)
sum: 55 count: 10
ans =
10
function [n total] = possum(limit)
total = 0;
n = 0;
while total <= limit control statement
n = n + 1;
loop body
total = total + n;
end
fprintf('sum: %d count: %d\n', total, n);
while conditional
block
end
if conditional
block
end
Difference:
while condition is evaluated repeatedly
block is executed repeatedly as long as condition is true
Problem: given a vector, v, of scalars, create a
second vector, w, that contains only the non-
negative elements of v
Traditional solution:
w = [];
jj = 0;
for ii = 1:length(v)
if v(ii) >= 0
jj = jj + 1;
w(jj) = v(ii);
end
end
MATLAB provides a more elegant solution:
w = [];
for ii = 1:length(v)
if v(ii) >= 0
w = [w v(ii)];
end
end
The ultimate solution needs only a single line: