How Do Assignment and Deletion Work with an Empty Index on the Left Hand Side ?
Show older comments
I've always thought that indexing with an empty array on the LHS of an = is a no-op for the variable on the LHS (there could be side effects of the evaluation of the RHS).
For example
% Case 1
A = [1 2;3 4];
A([]) = 5
But, assigning a non-scalar on the RHS result in an error
% Case 2
try
A([]) = [5,6];
catch ME
ME.message
end
Why doesn't Case 1 result in an error insofar as it also had a different number of elements on the left and right sides?
Using the deletion operator on the RHS with an empty index on the LHS reshapes the matrix
% Case 3
A = [1 2;3 4];
A([]) = []
Why does a request to delete nothing from A change A?
But that doesn't happen if A is column vector
% Case 4
A = [1;2;3;4];
A([]) = []
Deletion with a non-zero dimension of an empty index also reshapes the LHS
% Case 5
A = [1 2;3 4];
A(double.empty(0,1)) = []
A = [1 2; 3 4];
A(double.empty(1,0)) = []
I suppose Cases 3 and 5 are related to deleting a specific (non-empty) element from a matrix
% Case 6
A = [1 2;3 4];
A(3) = []
But I'm surprised that the result is not a column vector.
Are any/all of these results following a general rule? Pointers to relevant documentation would be welcome. I couldn't find any.
2 Comments
Another set of corner cases without a public design document/standard to refer to.
On this one I don't think there's a word said anywhere in the doc.
Just out of curiosity, can you give an example of useful code that deliberately does a nul assignment?
I see cases in which a computed reference does expect a result but yields a nul instead in which case it is an error; I suppose the exercise could be seeing what the result of that might be? For comparison, my practice is to test the result for being empty first, not to rely on default behavior in cases where it is known that indeed, there may not be anything to satisfy the condition. Sometimes there's alternative action, sometimes its a do-nothing, sometimes it actually is an error, but have to handle each.
Accepted Answer
More Answers (0)
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!