Matlab Reference Guide Arithmetic: Semicolon
Matlab Reference Guide Arithmetic: Semicolon
Matlab Reference Guide Arithmetic: Semicolon
Arithmetic
Basic arithmetic operators work like you’d expect; parentheses can be used to group terms:
Basic operators:
+ * / ^ >> 2*(3+10)
Grouping: ( ) ans = 26
>> 2^3
The ^ operator does exponentiation, so
2^3 ans = 8
computes 23
= 2 * 2 * 2 = 8.
Variables
Variables are just places where you can store values. Variable names can be almost anything, except they
can’t start with a number or contain spaces or operators.
Assignment operator: = >> a = 10
a = 10
A useful way to think about this operator is to >> a + 2
read it as “gets” that is the first example on the ans = 12
right would be “a gets 10”.
>> a_long_variable_name = 100
You can stop Matlab from printing the value a_long_variable_name = 100
after any line of code by adding a semicolon
(
;)
to the end of the line. >> a_string = 'alpaca';
Expressions and Values
A value is simply a concrete piece of data it could be a number, a string, or a matrix (more on these
later). An expression is a piece of code that can be evaluated to produce a value. So 10 is a value, and
5+5 10
, 20 / 2
, and are all expressions whose value is 10. If we type a = 10 a
, then is also an
expression whose value is 10.
Comparison Operators and Boolean Expressions
Boolean expressions evaluate to either true
or
false
, represented in Matlab as 1 and 0. Comparison
operators are the simplest kind of boolean expressions:
Comparison operators: >> 5 < 10 % (true)
< (less than) ans = 1
> (greater than) >> 5 >= 10 % (false)
<= (greater than or equal to) ans = 0
>= (less than or equal to)
== (equal to) >> a = 10
~= (not equal to) >> a == 10 % (true)
A common mistake is to mix up
=
and ==
. ans = 1
Remember that
=
is the assignment operator, and
means “gets”, whereas == means “is equal to”.
Control Flow: if statements and for loops
We can make decisions about what to do based on the value of a boolean expression using an if
statement , and we can repeat some lines of code many times using a
for loop. You can specify the range
of values a for [a,b,c]
loop’s variable takes on using brackets ( 1:10
) or using a range ( ).
if <condition> >> if 5 < 10
<do this if condition is true> a = 100;
else else
<do this if condition is false> a = 200;
end end
>> a
If you don’t want to do anything if the condition is false, a = 200
you can leave out the else clause.
Range operator: >> 1:5
a:b gives the range of values from a to b inclusive. ans = 1 2 3 4 5
a:x:b gives the range from a to b counting by x >> 1:3:10
ans = 1 4 7 10
for <loop_var> = <range of values> total = 0;
<do this for each value of for i = 1:5
loop_var> total = total + i;
end end
>> total
You can also simply give a list of values you want total = 15
loop_var to take on, e.g.,
[1, 2, 3, 4, 5] is
equivalent to
1:5 .
Calling Functions
Matlab has lots of extremely useful builtin functions. Typically, there are three things involved in calling
a function: the function name, its
arguments , and its
return value
. Arguments are passed into the
function, and the return value is the result.
Anatomy of a function call: >> sqrt(9) % square root
return_value = ans = 3
function(arguments); >> abs(9) % absolute value
ans = 9
If you leave out
return_value = , Matlab will >> big_llama = upper('llama')
assign the return value to
ans as with any unassigned big_llama = 'LLAMA'
value.
>> help upper
Find out how to use any builtin function: (documentation prints)
help <functionname>
% are these strings equal?
Some functions take more than one argument, >> strcmp('llama', 'alpaca')
separated by commas: ans = 0 % false not equal
function(arg1, arg2 , ... )
Writing New Functions
Remember that a function call has a name, arguments, and a return value. To define a function, we create
a file that specifies the name, arguments, and some code that calculates the return value. The filename
should match the name of the function, with a .m extension.
Anatomy of a function definition:
function [ output ] = function_name( input_args )
<write some code here that assigns a value to the output variable>
end
This code should go in a file called function_name.m. Then you can call the function as we saw above:
out = function_name( iargs );
It’s possible to write a function that has no return value and/or no input args. In this case, you simply
leave the brackets and parens empty, respectively, i.e., [] = function_name() . However, usually
a function isn’t very useful unless it computes an output based on some input variables.
To create a new function, click the New button in the Matlab toolbar and select Function. Matlab
creates a file and fills in the default structure similar to the above example.
Example function definitions: Example usage:
function [area] = square_area(side_length) >> sq_area(10)
area = side_length * side_length; ans = 100
end >> b = 5;
>> bsq = sq_area(b)
Functions can take multiple arguments and return multiple bsq = 25
outputs, as in the following example:
function [area, perim] = rect_info(side1, side2) >> [a,p] = rect_info(5,10)
area = side1 * side2; a=50
perim = 2*(side1 + side2); p=30
end
>> rect_info(10,10)
Note that if you don’t assign the outputs to variables, matlab will
ans = 100
only print the first output (
area
, in this case).
Reading and Writing Images
Basic image functions: >> img = imread('llama.jpg');
imread read an image from a file >> img = img 50;
imshow display an image in a figure >> imshow(img);
window >> imwrite(img,'darkllama.jpg');
imwrite save an image to a file
Remember a semicolon when you work with
images, or Matlab will print out the entire image
as a matrix (that’s a lot of numbers!)
Matrices
A matrix is just a grid of numbers. These are really easy to work with in Matlab in fact, that’s what the
“Mat” stands for. Because images are made up of a grid of pixels, it’s natural to think of them as matrices.
Creating new matrices: >> M = zeros(2,3)
zeros create a matrix full of zeros M =
ones create a matrix full of ones 0 0 0
0 0 0
When specifying the size of a matrix of the >> N = ones(3,2)
index of an element, you always specify rows N =
then columns . So a 2by3 matrix has 2 rows 1 1
and 3 columns, and element (1, 2) of a matrix is 1 1
element in the first row and the second column. 1 1
Accessing individual elements: >> M(2,1)
M(i,j) the (i, j)th element of M ans = 0
>> M(2,1) = 100
This can be used either to get the value or to M =
set
it. 100 0 0
0 0 0
Elementwise arithmetic : If you use any >> M + 10
normal arithmetic operator with a matrix, the ans =
operation will be done to all of its elements. . 110 10 10
10 10 10
Color images are represented as 3dimensional >> img =
matrices this means each element has 3 imread('color_llama.jpg');
indices, a row, column, and a color channel. A >> img(1,1,1)
color image has three channels to store the red, ans = 45 % (red channel value)
green, and blue color values of a pixel. >> img(1,1,3)
ans = 221 % (blue channel value)
Slicing allows you to get a submatrix of a
larger matrix. Use :
instead of an index to look >> img(1,1,:) % (all channels)
up all indices along that dimension. ans = 45 52 221
>> green_image = img(:,:,2);
% green_image now contains the
% entire (2D) green channel image
Getting the size of a matrix:
size return the dimensions of a matrix >> size(img)
ans = 400 600 3
>> size(green_image)
ans = 400 600
Functions
* Functions marked with an asterisk are not builtin so you must be in the same folder as the code
(functionname.m) to use them.
Math:
abs, sqrt, min, max, sum, mod
Strings:
upper
Turtles*: Turtle, turtleForward, turtleTurn, turtleDown, turtleUp, turtleSquare
Matrices:
size, circshift, cat
Images:
imread, imshow, imwrite, imresize
Logical operations:
or, and, not
Figure management:
figure, close, clf
Workspace management:
clear, clc