MATLAB Short Course 3: Flow control MATLAB functions
Contents
- if
- branching using "if" to get the sign of x
- branching using "if" to get the absolution value
- alternative simplified version for absolute value
- for loop
- sum of inverse squares
- "while" loop
- loop can be stop using "break" or "continue"
- print all prime factors, if n is composite
- anonymous MATLAB functions (for simple ones)
- general MATLAB functions (for complicated ones)
if
n = 1; if (n==2) print("n = 2"); end % if-else if (n==2) print("n = 2"); else print("n is not 2"); end

branching using "if" to get the sign of x
x = randn(1) % get the sign of x if (x>0) s = 1; elseif (x==0) s = 0; else % alternatively: elseif (x<0) s = -1; end s
x = 0.3192 s = 1
branching using "if" to get the absolution value
% the absolute value (same as "abs" in matlab) x = randn(1) if (x>0) x = x; elseif (x==0) x = 0; else x = -x; end x
x = 0.3129 x = 0.3129
alternative simplified version for absolute value
x = randn(1) if (x<0) x = -x; end x
x = -0.8649 x = 0.8649
for loop
for variable = start_value:step:end_value
% calculate the sum of integers from 1 to 100 S = 0; for n = 1:1:100 S = S+n; end S
S = 5050
sum of inverse squares
S = 1 + 1/2^2 + 1/3^2 + ....
format compact format long N = 10000; S = 0; for n = 1:N S = S+1/n^2; end [S; pi^2/6]
ans = 1.644834071848065 1.644934066848226
"while" loop
sum inverse squares using while loop
N = 10000; n = 1; S = 0; while (n<=N) S = S + 1/n^2; n = n+1; end S % Another version, when "n = n+1" is executed first N = 10000; S = 0; n = 0; while (n < N) n = n+1; S = S + 1/n^2; end S % yet another version using "break" N = 10000; S = 0; n = 1; while (1) S = S + 1/n^2; n = n+1; if (n==N+1) break; end end
S = 1.644834071848065 S = 1.644834071848065
loop can be stop using "break" or "continue"
k = 1; while (1) k = k + 1; if (k>10) break; % break and stop the loop end end k
k = 11
print all prime factors, if n is composite
for n = 2:20 if (isprime(n)) continue; % continue to the next loop, and forget the rest (inside the loop) end pf = factor(n); disp(['The prime factors of ' num2str(n) ' is ' num2str(pf)]); end
The prime factors of 4 is 2 2 The prime factors of 6 is 2 3 The prime factors of 8 is 2 2 2 The prime factors of 9 is 3 3 The prime factors of 10 is 2 5 The prime factors of 12 is 2 2 3 The prime factors of 14 is 2 7 The prime factors of 15 is 3 5 The prime factors of 16 is 2 2 2 2 The prime factors of 18 is 2 3 3 The prime factors of 20 is 2 2 5
anonymous MATLAB functions (for simple ones)
myfun = @(t) sqrt(1+t.^2);
general MATLAB functions (for complicated ones)
% save the function as "myfun1.m" % you can call it like % y = sin(1) or y = sin(linspace(0,2*pi,101)) % function y = myfun1(x) % y = sqrt(1+x.^2);