Foundations of computer programming in MATLAB
Expressions
Let’s launch MATLAB
and try it out! The Command Window
should have a command prompt >>
, which is begging for us to enter something. This something is called an expression. Expressions can be something as simple as a number, say 5
. If we enter this, and press the return
(or enter
) key, we should see the following occur.
>> 5
ans =
5
What just happened? The interpreter read the expression 5
, evaluated it, then printed it.
Let’s have the interpreter do some arithmetic for us.
>> 7 - 5
ans =
2
Pretty much what you would expect. But there’s something new here: an operation was performed. This operation was indicated by the -
operator, which subtracts the second number from the first. The numbers 7
and 5
are called the operands.
More complex expressions can be evaluated, as well. Parentheses ()
group expressions to created a nested expression. Here is an example.
>> (3 + 5) - (8/(3 + 1))
ans =
6
Exercises
Evaluate the following expressions.
2^7
2*53
2 * 53
'hello'
[1, 2, 3]
Assignment
We can store the output of the evaluation of an expression by assigning it to a variable name.
When we are working in the MATLAB
Command Window
, assignments are saved in the Workspace
. We can assign several variables, then recall them by name.
Example
Let’s store some variables and reuse them.
x = 3;
y = 5;
z = x*y;
disp(z)
Exercise
Store the following variables in a Workspace
.
a = 2^3;
B = 78 - 32;
total_number_of_people = 5;
costume = 'duck';
Mask = 'jason';
Now, complete the following tasks.
- Assign
a - B
to a new variablec
. - Assign
['He wore a ',costume,'costume, and a ',Mask,' mask.']
to the variablesentence
. - Assign
total_number_of_people^2
to the variabletotal_number_of_square_people
. - Try assigning
a*B
to the variablea times b
. - Try assigning
a - B
to the variablea-B
. - What limitations have you discovered in variable names?