#### Transcript link 12 - EEIC Faculty

```•
MATLAB – While Loops
Topics Covered:
Loops in MATLAB
- while loops
College of Engineering
Engineering Education Innovation Center
ENG 1181
•
ENG 1181
EXAMPLE OF break
What will this loop display?
a = 0;
while a<10
a = a + 1;
if (a == 5)
break
end
disp (a)
end
…
1
2
3
4
•
ENG 1181
EXAMPLE OF continue
What will this loop display?
a = 0;
while a<10
a = a + 1;
if (a == 5)
continue
end
disp (a)
end
1
2
3
4
6
7
8
9
10
•
ENG 1181
EXAMPLES OF while–end LOOPS
Find the smallest number divisible by both three
and five whose square is greater than 3325?
Another version with all conditions in the while !
y = 0; x=3;
while (y <= 3325)
x = x + 3;
if rem(x,5) == 0
y=x^2;
end
end
x
x =
60
>>
Note negation
x =3;
while ~(rem(x,5) == 0
& x^2 <= 3325)
x = x + 3;
end
fprintf(‘The number is
%d\n,x)
The number is 60
>>
•
ENG 1181
EXAMPLES OF while–end LOOPS
Script File
clc
clear
% Script file calculates the standard deviation of a function using a while loop
% and employs the corresponding MATLAB function call to verify correctness.
n=50;
% Size of random vector
% Create a random vector of size n
x=rand(n,1);
% Calculate mean of random vector x using a WHILE loop
…….
…….
% Display mean results of MY calculation and Matlab calculation
…….
…….
% Calculate standard deviation of random vector x using a WHILE loop
…….
…….
% Display standard deviation results of MY calculation and Matlab calculation
…….
…….
•
ENG 1181
EXAMPLES OF while–end LOOPS
clc
clear
% Script file calculates the standard deviation of a function
% using a while loop and employs the corresponding
% MATLAB function calls to verify correctness.
n=50;
% Size of random vector
% Create a random vector of size n
x=rand(n,1);
% Calculate mean of random vector x using a WHILE loop
sum_it1 = 0;
% Set sum_it to zero
i = 1;
% Set loop counter to start at 1
while i<=n
sum_it1=sum_it1+x(i);
i=i+1;
end
my_mean = sum_it1/n; % Complete my calculation
std_mean = mean(x);
% MatLab calculation
% Display mean results of my calculation and Matlab calculation
fprintf('\nMY_MEAN = %8.6f, MAT_MEAN =
%8.6f\n',my_mean,std_mean)
% Calculate mean of random vector x using a WHILE loop
sum_it2 = 0;
% Set sum_it to zero
k = 1;
% Set loop counter to start at 1
while k <= n
sum_it2 = sum_it2 + (x(k)-my_mean)^2;
k = k +1;
end
my_std = ((sum_it2/(n-1)))^(1/2); % Complete my calculation
std_dev = std(x);
% MatLab calculation
% Display std_deviation results
fprintf('\nMY_STDDEV = %8.6f, MAT_STDDEV =
%8.6f\n',my_std,std_dev)
•
ENG 1181
EXAMPLES OF while–end LOOPS
Script File
clc
clear
%This script file calculates the sum of the cubes of the numbers 1100000, using both a while loop and the sum function
%initialize variables
s=1;
% or s = 0; k = 1;
k=2;
%Calculate sum using while loop
while k<=100000
s=s+k^3;
k=k+1;
end
s
%calculate sum using sum function
s=sum((1:100000).^3)
Command Window Output
s=
2.5001e+19
s=
2.5001e+19
>>
```