recipes : programming : Writing better code : Multiplying arrays without using loops

Problem

A have two arrays (or vectors) of the same size, how do I perform an element by element mathematical operation without using loops?

SolutionAddition (+) and subtraction (-) work the same on both matrices and scalars. In other words, in the case of scalars, if A=3 and B=5 then the Matlab expression A+B will yield the answer 8. This also works for vectors or arrays, with A+B yielding element-wise addition (or subtraction, if that's what you asked for). Here are some examples.

%Adding two vectors A=[1,2,3]; B=[5,5,5]; >> A+B ans = 6 7 8 %Subtracting two matrices >> A=[10,20; 30, 40] A = 10 20 30 40 >> B=[1,2; 3, 4] B = 1 2 3 4 >> A-B ans = 9 18 27 36

Things are slightly different for element-wise multiplication, division, and exponents. For multiplication, rather than using the * operator we use .*. The reason for this is because * is reserved for matrix multiplication

A=[1,2,3]; B=[5,5,5]; >> A+B ans = 6 7 8 >> A.*B ans = 5 10 15 >> A./B ans = 0.2000 0.4000 0.6000 >> A.^B ans = 1 32 243

Arrays and vectors must be of the same size for element-wise operations to succeed. Note that "size" doesn't simply mean the same length. It means they must have the same number of elements *in each dimension*. Consequently, Matlab does not let you add a row vector and a column vector even if both have the same length.

Using MATLAB's built-in functions for working with matrices is important: they simplify your code, make it easier to read, and will work faster. Generally speaking, if you find yourself writing a lot of loops (particularly nested loops) then there is likely to be a more simple way of performing the task. The element-wise operations shown here are one way of achieving this. To learn more about it, read the page on vectorising code.