Clear Filters
Clear Filters

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

1 view (last 30 days)
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

Accepted Answer

Voss
Voss on 11 Jun 2020
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);

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!