0
votes

I am struggling with some basic vectorization operations in Octave.

Lets say I instantiate a 10*10 matrix A. A = magic(10) I also instantiate a vector x. x = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]

I want to use a vectorized operation, instead of for loops to fill in an empty vector e. e = zeros(10,1)

for i = 1:10
  for j = 1:10
    v(i) = v(i) + A(i, j) * x(j);
  end
end

I have studied the the octave documentation chapter 19 about vectorization, and I believe that the only answer is v = A * x. But I am unsure, whether other options exist to vectorize this loop.

1
What is wrong with v = A * x? Looks like a perfect solution.Daniel
Sure, but I am right that it would be the only solution ? As per octave documentation, it would be.RlikeRun
There's also sum(A.*x.', 2), which uses element-wise multiplication with broadcasting. But matrix multiplication is likely to be a little faster, and it looks cleanerLuis Mendo

1 Answers

1
votes

Using multiplication is the best option, but there are other options, for example:

sum(A.*x.',2)

You often find such solutions when it comes to vectorizing loops like:

for i = 1:10
  for j = 1:10
    v(i) = v(i) + f(i,j);
  end
end

The intermediate step is a matrix which holds all solutions for f(i,j) (sum(A.*x.',2) in your example), then you accumulate replacing the + with a sum.