Examples of while loop in MATLAB

0

while loop to repeat when condition is true

Syntax

while expression

      Statements 

end

 

 

All Contributions

Sum a sequence of random numbers until the next random number is greater than an upper limit. Then, exit the loop using a break statement.

limit = 0.8;
s = 0;

while 1
    tmp = rand;
    if tmp > limit
        break
    end
    s = s + tmp;
end

Count the number of lines of code in the file (magic.m) . Skip blank lines and comments using a continue statement. continue skips the remaining instructions in the while loop and begins the next iteration.

fid = fopen('magic.m','r');
count = 0;
while ~feof(fid)
    line = fgetl(fid);
    if isempty(line) || strncmp(line,'%',1) || ~ischar(line)
        continue
    end
    count = count + 1;
end
count

Use a while loop to calculate factorial(10).

n = 10;
f = n;
while n > 1
    n = n-1;
    f = f*n;
end
disp(['n! = ' num2str(f)])

The result is :

n! = 3628800

total contributions (3)

This topic belongs to these lists

need a help?


find thousands of online teachers now

New to examplegeek.com?

Join us