





















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






















index is the loop variable and expr is the loop control expression expr = first:incr:last for i = 1: Stat eme nt 1 … Stat eme end^ nt n
for i = 1:2: Stat eme nt 1 … Stat eme end^ nt n
i=10 i=
for i = [5 9 7] Stat eme nt 1 … Stat eme end^ nt n
i=
for i = [1 2 3; 4 5 6] Statement 1 … Statement n end = 6 i^3 Loop index can be a vector
Example 4.3—Calculating the Day of Year (Page 158)
for ii = 1:100 square(ii) = ii^2; square_root = ii^(1/2); cube_root(ii) = ii^(1/3); end ii = 1:100 square(ii) = ii.^2; square_root = ii.^(1/2); cube_root(ii) = ii.^(1/3);
300 separate lines of code
4 lines of code
The break and continue statements
for ii = 1:5 if ii == 3; end^ break; end^ fprintf(‘ii = %d\n’, ii); disp([‘End of loop!’])
test_break ii = 1 ii = 2 End of loop!
for ii = 1:5 if ii == 3; end^ continue; end^ fprintf(‘ii = %d\n’, ii); disp([‘End of loop!’])
test_continue ii = 1 ii = 2 ii = 4 ii = 5 End of loop!
for ii = 1:3 for jj = 1: product = ii * jj; fprintf(‘%d * %d = %d\n’, ii, jj, product); end^ end
test_nested_loops 1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
4.3 Logical Arrays and Vectorization
for ii = 1:size(a,1) for jj = 1:size(a,2) if a(ii,jj) > 5; a(ii,jj) = sqrt(a(ii,jj)); end ;product = ii * jj; end^ ;fprintf(‘%d * %d = %d\n’, ii, jj, product); end
Vectorized approach is faster b = a > 5; a(b) = sqrt(a(b));