简体   繁体   中英

Vectorization Octave

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM