How do I subtract all the values of one vector, one by one form an other vector, without using a for loop?
2 views (last 30 days)
Show older comments
Rasmus Stenholt-Jacobsen
on 26 Nov 2015
Commented: Star Strider
on 26 Nov 2015
I am trying to optimize a for loop, where i want to remove an inner for loop by looping an entire vector, instead of looping each value of the vector.
I want to subtract all of the values from one vektor V, from an other vector B, so that I get a B(:)-V(n) vector, for each n value of V:
eksampel:
V = [1,2,3]
B = [4;11]
(The dimensions of the output vectors does not matter)
Result = [4-1,11-1;4-2,11-2;4-3,11-3]
0 Comments
Accepted Answer
Star Strider
on 26 Nov 2015
The bsxfun function is perfect for this:
V = [1,2,3];
B = [4;11];
Result = bsxfun(@minus, B, V)';
2 Comments
Star Strider
on 26 Nov 2015
My pleasure.
The meshgrid approach is correct, and in some situations preferable, for instance if you have several calculations involving the vectors. With one calculation, bsxfun is usually more efficient. This meshgrid approach also works for your problem:
[Vm,Bm] = meshgrid(V,B);
Result = Bm-Vm;
More Answers (0)
See Also
Categories
Find more on Problem-Based Optimization Setup in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!