Assign empty value(s) to matrix elements (to delete those elements) fails
15 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Walter Roberson
2016-4-11
It is intended behaviour. The deletion is detected by the syntax of [], not by the variable being empty.
2 个评论
Walter Roberson
2016-4-11
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.
更多回答(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!