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!