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

15 ビュー (過去 30 日間)
J-G van der Toorn
J-G van der Toorn 2016 年 4 月 11 日
コメント済み: Walter Roberson 2016 年 4 月 11 日
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?

採用された回答

Walter Roberson
Walter Roberson 2016 年 4 月 11 日
It is intended behaviour. The deletion is detected by the syntax of [], not by the variable being empty.
  2 件のコメント
J-G van der Toorn
J-G van der Toorn 2016 年 4 月 11 日
編集済み: J-G van der Toorn 2016 年 4 月 11 日
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 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 ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by