Professional Documents
Culture Documents
1 0 1 0
a b 0 then a b will yield
2 1 0 1
Real numeric data can also be use with logic operators. Since logic
operators expect logical input values, MATLAB converts nonzero
values to true and zero values to false before performing the
operation. Thus,
the result of ~5 is false (0 in the Command Window)
the result of ~0 is true (1 in the Command Window)
Logic operators may be used to compare a scalar value with an array.
For example, if
0 0
(displayed as in the Command Window).
0 0
Logic operators may also be used to compare two arrays, as long as
both arrays have the same size. For example, if
Hierarchy of Operations
switch (switch_expr)
case {case_expr_1, case_expr_2, case_expr_3}
Statement 1
Statement 2
...
otherwise
Statement 1
Statement 2
...
end
The switch_expr and each case_expr may be either numerical or
string values.
switch (value)
case {1,3,5,7,9}
disp('The value is odd.');
case {2,4,6,8,10}
disp('The value is even.');
otherwise
disp('The value is out of range.');
end
The try/catch Construct
The try/catch construct is a special form branching construct
designed to trap errors. Ordinarily, when a MATLAB program
encounters an error while running, the program aborts. The try/catch
construct modifies this default behavior. If an error occurs in a
statement in the try block of this construct, then instead of aborting,
the code in the catch block is executed and the program keeps
running. This allows a programmer to handle errors within the
program without causing the program to stop.
The general form of a try/catch construct is as follows:
try
Statement 1
Statement 2
...
catch
Statement 1
Statement 2
...
end
% Initialize array
a = [ 1 -3 2 5];
try
% Try to display an element
index = input('Enter subscript of element to display: ');
disp( ['a(' int2str(index) ') = ' num2str(a(index))] );
catch
% If we get here an error occurred
disp( ['Illegal subscript: ' int2str(index)] );
end