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
0 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!