Matlab uses decision and loop structures to control program execution. The constructs are similar to VB though the actual form may be different. The following structures are available in Matlabif statements
switch statements
for loops
while loops
break statements
There are three types :
if expression
statements
end
if (A(1,1) > A(1,2) )
A(2,1) = 2.0 * pi
end
if expression
statements
else
statements
end
if (sum(A(:,2)) > 10 )
A(1,1) = A(1,1) + B(1,1)
A(2,1) = pi*A(2,1)
else
A(1,1) = A(1,1) + A(1,1);
A(2,1) = 0.5 * pi
end
if expression_1
statements
elseif expression_2
statements
elseif expression_3
.......................else
statements
end
Build your own example here
If you need to execute different commands for different results based on a single condition then the switch case is the control you needswitch expression [ can be a scalar or a string ]
case test1
command set 1
case test 2
command set 2
......................................otherwise
command set last
endIf expression is scalar then case is executed if the scalar value matches the expression in the test
If expression is string then case is executed if the strings match
x = 3.0;
units = 'mm';switch units
case {'in','inch'}end
y = 2.54*x; % converts to centimeterscase {'m','meter'}
y = x*100; % converts to centimterscase { 'millimeter','mm'}
y = x/10;
disp ([num2str(x) ' in ' units ' converted to cm is :' num2str(y)])
case {'cm','centimeter'}
y = x;otherwise
disp (['unknown units:' units])
y = nan;Note that the test expression in the case statements have more then one match
The syntax for the for loop isfor x = array
commands
endThe commands between the for and end statements are executed once for every column in array
for n = 1: length(A(1,:)) % default stepsize = 1
xa(n) = A(1,n)^2;
for m = 1:2:length(xa) % in steps of 2
m
X(n,m) = n*m; % whats happenning
% how will you check whats happenning
end
end
The general form of the while loops arewhile expression
commands
end
count = 1; num = 2;
while count < 16
cnum= [count num];
disp(cnum)
num = num*2;
count = count + 1;
end
Break statements allow you to exit for and while loop prematurely
count = 1; num = 2;
while count < 16
cnum= [count num];
disp(cnum)
num = num*2;
count = count + 1;
if count >= 10
break
end
end