Scripts, Execution Control, Loops, and Functions

Created


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: ~A returns an array with the same dimensions as A; the new array has ones where A is zero and zeros where A is non-zero.
  • & AND: A & B returns an array with the same dimensions as A; the new array has ones where both A and B is nonzero and zeros where A or B is zero.
  • | OR: A | B returns an array with the same dimensions as A; the new array has ones where at least one elemnt in A or B is nonzero and zeros where A and B are 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)
  • function is 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_name is user-defined and must match the *.m file name.
  • Parenthesis holdl the inputs that will be passed to the function.

Example function that computes y=x2+5y = x^2 + 5

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)