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 中查找有关 Logical 的更多信息

标签

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by