Assign empty value(s) to matrix elements (to delete those elements) fails
15 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
J-G van der Toorn
il 11 Apr 2016
Commentato: Walter Roberson
il 11 Apr 2016
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 Commenti
Risposta accettata
Walter Roberson
il 11 Apr 2016
It is intended behaviour. The deletion is detected by the syntax of [], not by the variable being empty.
2 Commenti
Walter Roberson
il 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!