1

I have a long MATLAB code which takes a lot of time due to numerous for loops. I try to eliminate them but it looks like I do not understand the vectorization concept. To be more specific, consider the following simple example with two vectors with different sizes:

a1=[1 2];
a2=[1 2 3];

I want to computea1/a2 in a "piece-wise" sense. For that, I use the following for loops

div=0;
for i=1:size(a1,2)
 for j=1:size(a2,2)
  div=div+a1(i)/a2(j);
 end
end

How can I vectorize such two for loops? Many thanks!

3 Answers 3

1

Two good options: bsxfun and ndgrid. Given two row vectors:

a1=[1 2];
a2=[1 2 3];

bsxfun

The old-school way is with two repmat calls. Virtual replication can now be done with bsxfun:

divM = bsxfun(@rdivide,a1,a2');
div = sum(divM(:))

Faster and more memory-efficient than repmat.

ndgrid

When you think "all combinations", think ndgrid.

[ii,jj] = ndgrid(1:numel(a2),1:numel(a1))
divM = a1(jj)./a2(ii);
div = sum(divM(:))
Sign up to request clarification or add additional context in comments.

1 Comment

@LuisMendo You're right! Ah, curse you! Why didn't i think to just invert a2?
1

You can do it with just matrix multiplication: a column vector times a row vector gives a matrix with all combinations of element-wise products:

divs = a1(:) * (1./a2(:)).';
div = sum(divs(:));

Comments

0

This would work for you.

a1=[1 2];
a2=[1 2 3];
div_matrix = a1' ./ repmat(a2, [size(a1,2), 1])
sum(div_matrix(:))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.