bsxfun(minus) vs normal minus

조회 수: 5 (최근 30일)
DIMITRIOS THEODOROPOULOS
DIMITRIOS THEODOROPOULOS 2018년 7월 3일
답변: Rik 2018년 7월 3일
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
James Tursa
James Tursa 2018년 7월 3일
편집: James Tursa 2018년 7월 3일
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
DIMITRIOS THEODOROPOULOS 2018년 7월 3일
Ι dont compare anything special.I just try to understand how bsxfun works.To be honest i still dont understand. For example in the first loop what operations are executed??I expect from each element of the first row of A to substract each element of the first row of X.

댓글을 달려면 로그인하십시오.

채택된 답변

Rik
Rik 2018년 7월 3일
Have you read the documentation of bsxfun?
Input arrays, specified as scalars, vectors, matrices,
or multidimensional arrays. Inputs A and B must have
compatible sizes. For more information, see Compatible
Array Sizes for Basic Operations. Whenever a dimension
of A or B is singleton (equal to one), bsxfun virtually
replicates the array along that dimension to match the
other array. In the case where a dimension of A or B is
singleton, and the corresponding dimension in the other
array is zero, bsxfun virtually diminishes the
singleton dimension to zero.
This means the following:
A=[1 2];% 1 by 2
B=[3;4];% 2 by 1
%A will be replicated along the first dimension to make it match B
%B will be replicated along the second dimension to make it match A
%then an element-wise operation can be performed:
C1=bsxfun(@minus,A,B);
C2=repmat(A,size(B,1),1)-repmat(B,1,size(A,2));

추가 답변 (1개)

Guillaume
Guillaume 2018년 7월 3일
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.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by