Matrices
A variable that contains a single value like my_age in the earlier example is treated by Matlab as 1-by-1 matrix of numbers. This may sound like a complication but (for mathematicians and programmers at least) it turns out to make life much simpler in many ways.
A feature of Matlab is that it can calculate more than one answer in the same expression:
my_scores = [1 2 3 4 5];
my_scores = my_scores + 2;
my_scores
my_scores =
3 4 5 6 7
You can see that Matlab has added 2 to all the values inside the variable. The variable my_scores in the example above is a 1-by-5 matrix because it has 1 row and 5 columns. People sometimes call this a 'row vector' just to be confusing. I will stick to using the word 'matrix'.
Note that rounded brackets, or any other sort of bracket, will not work to enclose matrices:
(1 2 3 4 5) + 2
??? (1 2 3 4 5) + 2
|
Error: Unexpected MATLAB expression.
Try to predict what will happen here:
[1 2 3 4 5] + [1 2 3 4 5]
and here
[1 2 3 4 5] * [1 2 3 4 5]
Were you right in both cases? Unless you have previous experience with this sort of thing then probably not. If you are familiar with matrix arithmetic it will all come as no surprise to you.
Note that using .* ( a multiply with a dot in front of it) does get the result you expect:
[1 2 3 4 5] .* [1 2 3 4 5]
ans =
1 4 9 16 25
There is a dotted version of divide too, try it out for yourself.