With a = 1:4 and b = [], why does a(1) = [] remove an element while a(1) = b returns an error?

4 vues (au cours des 30 derniers jours)
Skyx
Skyx le 7 Juil 2018
Commenté : Skyx le 7 Juil 2018
Some example code:
a = 1:4;
a(1) = [];
assert(isequal(a,2:4))
b = [];
a(1) = b; % Returns an error.
What is going on here?
I am using R2017b.

Réponse acceptée

Stephen23
Stephen23 le 7 Juil 2018
Modifié(e) : Stephen23 le 7 Juil 2018
Basically this is a "special" syntax:
X(...) = []
Do not think of the RHS as being a variable. Think of it as being just that exact syntax.
If MATLAB was consistent (which it isn't), then both cases would be interpreted as attempts to allocate an empty array to a non-empty part of an array (which of course is not possible, hence the error). However because this allocation would always be an error and the syntax is really quite convenient, apparently the designers of MATLAB took this compact syntax (that is otherwise entirely wasted) and changed it by definition to remove rows/columns/... from arrays. So the answer to your question is "by definition".
Note that it really does not matter how you try to define the RHS, you will get an error:
>> A = 1:4;
>> B = [];
>> A(1) = B
??? In an assignment A(I) = B, the number of elements in B and
I must be the same.
>> A(1) = zeros(0)
??? In an assignment A(I) = B, the number of elements in B and
I must be the same.
>> B = 5:9;
>> A(1) = B(2:1)
??? Improper assignment with rectangular empty matrix.
>> A(1) = 1:0
??? Improper assignment with rectangular empty matrix.
The only way is to use that exact syntax, because that is its purpose by design:
>> A = 1:4;
>> A(1) = []
A =
2 3 4
  4 commentaires
Image Analyst
Image Analyst le 7 Juil 2018
Skyx, what different behavior do you want it to do? Do you want to delete/remove elements? Set elements to null but not remove them (I believe requires a cell array)? Something else???
Skyx
Skyx le 7 Juil 2018
I was thinking that if I have an array of my own class (say, MyClass), it might be nice to be able to remove elements not only with the ... = [] syntax, but also with something akin to ... = MyClass.empty. However, since, the ... = [] syntax is really a special case, I guess I shouldn't be trying for this.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by