Now that we have an understanding of arrays and how to define them, let’s learn how to work with them using operations.
matlab
arr1 = [1 2 3 4 5];
arr2 = [2 4 5 1 2];
arr1 + arr2; % output: 3 6 8 5 7
arr1 - arr2; % output: -1 -2 -2 3 3
As we can see, adding and subtracting arrays is pretty straightforward, however, what do you think will happen if two arrays of different sizes are added or subtracted? Well, we can always test it!
matlab
arr3 = [1 2 4 3];
arr1 + arr3; % This will error due to the different array sizes
So, now we know if two arrays of different sizes are added or subtracted, then an error will throw!
Earlier we had learned about the dot operator for multiplication and division of arrays when we talked about character arrays. The same concept applies here as well where the multiplication operator (*) multiplies the arrays using array, or matrix, multiplication and the dot multiplication operator (.*) multiplies each corresponding array value together, hence why the size must be the same for this. Let’s see an example.
matlab
% From before
arr1 = [1 2 3 4 5];
arr2 = [2 4 5 1 2];
arr1 .* arr2; % output: 2 8 15 4 10
arr1 ./ arr2; % output: 0.5 0.5 0.6 4 2.5
In the code block above, the two arrays were multiplied and divided element-wise using the dot operator in combination with the multiplication and division operators. Let’s now try not using the dot operator and only use the multiplication operator. In order to do this, we must follow the rules of array/matrix multiplication where the inner dimension must be the same, otherwise, MATLAB will throw an error.
matlab
% From before
arr1 = [1 2 3 4 5]; % Row array from before
arr2 = [2 4 5 1 2]’; % Notice the apostrophe making arr2 a column array
% Dimension of arr1 is a 1x5
% Dimension of arr2 is a 5x1
arr1 * arr2; % output: 39
Notice that arr1 had a dimension of 1x5, or 1 row and 5 columns, and arr2 has a dimension of 5x1, or 5 rows and 1 column. So by multiplying arr1 and arr2, we were multiplying two arrays with dimensions 1x5 * 5x1 and got a 1x1 value back, which was 39.
The next thing we will talk about with array operations are exponents. We know from the MATLAB Operations tutorial, the exponent operator is the (^) symbol; this can be used to take the exponent of an array. Let’s try a couple examples.
matlab
% From before
arr1 = [1 2 3 4 5];
arr1^2; % This will error due to wrong size
arr1.^2; % output: 1 4 9 16 25
Using arr1 from before, we can try using the exponent operator without the dot operator, but it errors. This is because the exponent operator takes arr1 and multiplies it with itself. The problem here is that arr1 has the dimension 1x5, and if arr1 is multiplied by itself, then we have 1x5 * 1x5 which does not follow the rules of matrix/array multiplication, so an error is thrown.
However, if we were to use the dot operator with the exponent operator, then we are doing an element-wise exponent, which will work.