%% MATLAB Short Course 3: Flow control MATLAB functions

%% 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

%% 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

%% alternative simplified version for absolute value
x = randn(1)
if (x<0)
x = -x;
end
x

%% 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

%% 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]

%% "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

%% 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

%% 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

%% 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);