Scripts, Execution Control, Loops, and Functions
Operators
Relational operators
<less than< =less than or equal to>greater than> =greater than or equal to==equal to~=not equal to
Logical operators
~NOT:~Areturns an array with the same dimensions asA; the new array has ones whereAis zero and zeros whereAis non-zero.&AND:A & Breturns an array with the same dimensions asA; the new array has ones where bothAandBis nonzero and zeros whereAorBis zero.|OR:A | Breturns an array with the same dimensions asA; the new array has ones where at least one elemnt inAorBis nonzero and zeros whereAandBare zero.&&Short-Circuit AND||Short-Circuit OR
Conditional Statements
If statements Execute or skip a set of operations based on the evaluation of a statement using
if logical_expression
statements
end
If there are more than one logical-expressions, then use parentheses.
If-else statements
if logical_expression
statements
elseif logical_expression
statements
else
statements
end
Case statements
switch input_statement
case value_1
statements
case value_2
statements
otherwise
statements
end
Loops
For loops
for loop_variable = m:s:n
statements
end
Where
m= the initial value of the loop variable.n= the final value of the loop variable.s= the step size that the loop variable will increment by each time the loop executes.
A continue statement can be used to avoid computing the log of a negative number:
x = [10,1000,-10,100];
y=zeros(size(x));
for k = 1:length(x)
if x(k) < 0
continue
end
y(k) = log10(x(k));
end
The result is y = 1, 3, NaN, 2.
While loop
while logical_expression
statements
end
Output
fprintf('text', A. ...) command prints information using special characters
\n % return
\r % beginning of a new line \b % backspace
\t % tab
‘’ % Apostrophe
\\ % Backslash
Functions
Variables used within the function file are not seen by the rest of the program.
You can name the file the same name as the function and give it a *.m extension.
function [output_variables] = function_name(input_variables)
functionis a keyword and must be placed on the first line of the file- The square brackets represent what variables int he functino file will be returned at function call.
function_nameis user-defined and must match the*.mfile name.- Parenthesis holdl the inputs that will be passed to the function.
Example function that computes
function [y] = eq_test(x)
y = x^2 + 5
end
Call it by using
>> c = eq_test(2)
If you are returning multiple values, you must provide two variables to be assigned to
>> [area, circum] = circle_comp(3)Linked from Computational Modeling