Why does single element null assignment succeed, but multiple element null assignment fails?

조회 수: 1 (최근 30일)
Can someone help me understand why this succeeds (CASE 1):
A = magic(3);
isFeasible = false;
A(isFeasible,1) = 0; % lhs is 0-by-1, rhs is 1-by-1
While this fails (CASE 2):
A = magic(3);
isFeasible = false;
A(isFeasible,:) = [0 0 0]; % lhs is 0-by-3, rhs is 1-by-3
'Unable to perform assignment because the size of the left side is 0-by-3 and the size of the right side is 1-by-3.'
In both cases the sizes of the left and right hand sides do NOT match, but an error is thrown only in the second case. This is unfortunate behavior because it means additional code is required for special cases. For example, instead of CASE 2, I would have to do something like:
A = magic(3);
isFeasible = false;
if any(isFeasible)
A(isFeasible,:) = [0 0 0]; % lhs is 0-by-3, rhs is 1-by-3
end

채택된 답변

Voss
Voss 2020년 6월 11일
Even though the sizes do not match, the first assignment succeeds because 0 is a scalar. MATLAB replicates scalars as necessary upon assignment. See here: https://blogs.mathworks.com/loren/2006/02/22/scalar-expansion-and-more-take-2/
In the second case, the right-hand side is not a scalar, so the sizes must match in order to do the assignment. A general solution would be to replicate the vector [0 0 0] vertically the number of times you need it:
A = magic(3);
isFeasible = false;
A(isFeasible,:) = repmat([0 0 0],numel(find(isFeasible)),1);

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by