필터 지우기
필터 지우기

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

조회 수: 17 (최근 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?

채택된 답변

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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by