# Matlab Vector Tricks

There are a lot of things we do in mathematics that are usually annotated using summation notation, but which are easily seen to be vector operations. To illustrate this, consider a very simple example that occurs often. Suppose that we have a vector v = (v1,v2,...,vn)T, and we need to find the sum of the absolute values of its elements. One way to do this would be to use a for loop.

total = 0; for i=1:length(v) total = total + abs(v(i)); end

This works, and it is easy to see what is happening in the code, but it is a bit hard to type on a Matlab command line, and it takes four lines of code. We could accomplish the same objective in one line.

total = abs(v)*ones(length(v),1)

As you can see, it is arguable that the one-line version is less transparent than the four-line version, but it avoids the tedious work by the programmer of elementwise operations, and it is arguable that it is more efficient for Matlab itself, since it is designed to do vector operations. Actually, there is an even simpler and more obvious way to do this particular computation.

total = sum(abs(v))

In the same way, we could vectorize the distance formula. Suppose that u = (u1,u2,...,un)T, and v = (v1,v2,...,vn)T, and we want to calculate the distance between the points u and v in Rn. We could do this as a for loop.

distance = 0; for i=1:length(v) diff = u(i)-v(i); distance = distance + diff*diff; end

Of course, there is a vector solution as well, that requires less work.

diff = u-v; distance = diff*diff';

We added one line of code in each case here, to try to prevent Matlab from computing the difference of vectors twice. We hope we save n additions in this way. It is not a big deal when n is small, but it could be significant in a large computation.

Similarly, there are ways to make vector operations out of other common mathematical sum operations. For example, suppose we want to approximate the integral of a function, say sin(x), over an interval [-π, π] using the trapezoidal rule. Recall that this means imposing a uniformly spaced partition π=x0<x1<xn on the interval, and then computing

[(sin(x0) + sin(xn))/2 + ∑i=2n-1 sin(xi) ](2π/n).

In Matlab, the following methods are equivalent.

x=-pi:.1:pi; y=sin(x); integral = (y(1)+y(length(y)))/2; for i=2:length(y)-1 integral = integral+y(i); end integral = integral*.1 --- integral = (y*ones(length(y),1)-.5*(y(1)+y(length(y))))*.1 --- integral = (sum(y)-.5*(y(1)+y(length(y))))*.1 --- integral = (sum(y(2:length(y)-1))+.5*(y(1)+y(length(y))))*.1

The moral of the story is that whenever you see a summation operation in Matlab, it is worth thinking for a minute about how you might convert the operation to a vector computation.

Assignment C is posted.

The test solution is available.

Department of Mathematics, PO Box 643113, Neill Hall 103, Washington State University, Pullman WA 99164-3113, 509-335-3926, Contact Us