15 Print "Pick Number between 1 & 10"
Input V
if V<1 or V>10 then 15
|
V = 0; % Initialize to value<1
% so it does the loop at least once
while V<1 | V>10
V = input('Pick Number between 1 & 10 ');
end
Loop Structures
|
---|
The code below is a simple example
of a FOR loop which prints the sum of the
squares of the sines of all angles
from 0 to pi/2 in increments of 0.001
|
SumTh = 0
For Theta=0 To 3.14 Step 0.001
SumTh = SumTh + sin(Theta)^2
Next
Print "Sum is ";SumTh
|
SumTh = 0;
for Theta=0 : 0.001 : 3.14;
SumTh = SumTh + sin(Theta)^2;
end
disp(['Sum is ' num2str(SumTh)]);
| Because of the vector nature of
Matlab, it is often possible to replace a FOR loop
with an array process. The code below creates an array called
Theta which contains all of the angles. It then
calculates the sines of all of the values in one statement.
This script runs about 10 times faster
than the previous code. (This is unimportant for a short script,
but for a script which takes several seconds or longer, this can
be significant.) Note the use of the array operator .^
to square the array of sines. This is required since the operation
sTheta^2 would perform the
matrix multiplication sTheta*sTheta ,
and would result in an error since sTheta
is not a square matrix.
|
|
Theta=[0 : 0.01 : 3.14];
sTheta = sin(Theta);
SumTh = sum(sTheta.^2);
disp(['Sum is ' num2str(SumTh)]);
| * * * * * * * BASIC * * * * * * *
| * * * * * * * MATLAB * * * * * * *
|
---|
|