next up previous contents
Next: 3.2.4 Special arrays Up: 3.2 Manipulating matrices and Previous: 3.2.2 Element-by-element array operations   Contents

3.2.3 Array-array operations

We can also perform mathematical operations between the individual elements of two arrays. This only works (and only makes sense) if the arrays are exactly the same shape, that is each array has the same number of rows and columns. Try this example.
% array-array operations
clear all;
m = [1 0 -1 4
    4 5 -6 7
    -2 2 2 1]

n = [ 1 2 3 4
    1 2 3 4
    1 2 3 4]


size(m) % Verify that both arrays have the same shape
size(n) 

m+n % add m to n, element by element
ans-m % subtract m from the result; should get n back
m - n % subtract n from m
2*m - n  

m*n % multiply each element of m by the corresponding element in n??

The + and - operators work like we expect but when we try m*n we get an error:
??? Error using ==> *
Inner matrix dimensions must agree.
MATLAB thought we wanted true matrix arithmetic, like we learned in a math class a long time ago. Recall that to multiply to matrices together the number of rows in the first must be the same as the number of the columns in the second (i.e., the ``inner'' dimensions of the two matrices must be the same). To do an element-by-element multiplication of two arrays, we use the ``dot'' version of the multiplication operator, .*. Try m.*n. Does it do what you expect? Look closely at the output and see that each element of the result is a product of the respective elements of each matrix. Division and exponentiation are similar in that the dot version of the operators are required for element-by-element operations. Try, m./n and m.^n. What is the difference between m.^2 and m^2? Explain.
next up previous contents
Next: 3.2.4 Special arrays Up: 3.2 Manipulating matrices and Previous: 3.2.2 Element-by-element array operations   Contents
Gus Hart 2005-01-28