bsxfun(minus) vs normal minus
Show older comments
i have X=eye(3) and A=magic(3) What is the difference between Result1=A-X and the Result2 with this loop
for i=1:3
Result2=bsxfun(@minus,A,X(i,:));
end
2 Comments
James Tursa
on 3 Jul 2018
Edited: James Tursa
on 3 Jul 2018
Run it and see. For one, your loop overwrites Result2 with each iteration, so you are not even doing the same calculations and thus you shouldn't expect them to match. And you don't define Y (was this supposed to be X?). What are you really trying to compare?
DIMITRIOS THEODOROPOULOS
on 3 Jul 2018
Accepted Answer
More Answers (1)
Guillaume
on 3 Jul 2018
In your loop, which as James pointed out, wouldn't do anything useful since it overwrites Result2 at each step, for each i,
bsxfun(@minus, A, X(i, :))
is exactly equivalent in term of result to
A - repmat(X(i, :), size(A, 1), 1)
but uses much less memory since it doesn't actually replicate the X row.
Note that since R2016b, which introduced implicit expansion, this is also the same as
A - X(i, :)
Before R2016b, the above would have resulted in an error.
Categories
Find more on Logical 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!