Assign empty value(s) to matrix elements (to delete those elements) fails

23 views (last 30 days)
Suppose
A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
When I assign empty values to a range of A, those elements are removed; a very elegant way to delete entries.
A(:,2) = []
A =
16 3 13
5 10 8
9 6 12
4 15 1
But this fails when I don't directly specify the empty value, but use an empty variable instead:
b = [];
A(:,2) = b
Subscripted assignment dimension mismatch.
Then I get an error, although it looks pretty much identical: I assign empty or I assign empty.
>> b=[],[],whos
b =
[]
ans =
[]
Name Size Bytes Class Attributes
ans 0x0 0 double
b 0x0 0 double
Is this intended behavior? Or is it a bug?
Rationale:
I have a function that calculates something based on the difference between two columns of a matrix (iterative, due to the nature of the calculation, which is beyond this discussion), which returns a vector-value for every column except the last one; there it returns empty. It would be very elegant if I could assign the result to a (pre-allocated) matrix, where the last iteration just removes the last column of the result matrix. (As I don't know how many columns will produce a result beforehand, I don't want to take that into account in the number of loop steps.)
for col = size(A,2):-1:1
B(:,col) = sortOfDifferentiator(A,'-column',col,'-order',2);
end
Where
% sortOfDifferentiator returns empty [] if column+order > number of input columns
I could of course use:
for col = size(A,2):-1:1
result = sortOfDifferentiator(A,'-column',col,'-order',2);
if ~isempty(result)
B(:,col) = result;
% ... but now I need to create an additional intermediate variable
% and the code looks more complex this way
end
end
Or is there another shorthand way to achieve this?

Accepted Answer

Walter Roberson
Walter Roberson on 11 Apr 2016
It is intended behaviour. The deletion is detected by the syntax of [], not by the variable being empty.
  2 Comments
J-G van der Toorn
J-G van der Toorn on 11 Apr 2016
Edited: J-G van der Toorn on 11 Apr 2016
That's a pity. It would have allowed for an nice programming construction. I would propose it as a syntax extension in future versions of Matlab.
Yet, it doesn't make sense that the result of an assignment with a constant is different than that of a variable. It's not very consequent. Apparently, the syntax
=[]
is doing something exceptional.
Walter Roberson
Walter Roberson on 11 Apr 2016
Most of the time when people compute an empty result, and assign it to something, it is an error that deserves reporting. The deliberate uses of it are far far fewer than the times it is an error.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!