%%% loops.m: to run this script, at the matlab prompt type %%% loops %%% %%% this is an example of for and if-then-else statements: %%% define an array filled with 15 random numbers, loop %%% through and if value < 0.5 then set to zero, otherwise %%% set to 1.0 echo on ep = 15; m = rand(15,1); for i = 1:ep, if m(i) < 0.5; m(i) = 0.0; else m(i) = 1.0; end end m; %%% Another example: Create a large random matrix, and divide by %%% 2 until its norm is under a threshold. Keep track of the %%% number of iterations and display it. The ";" at the end of %%% each line tells Matlab not to echo that line each time through %%% the loop. R = rand(4,4)*10000 * rand; iter = 0; while (norm(R) > .1) R = R / 2; iter = iter + 1; end sprintf('Number of iterations = %d', iter) echo off