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

4 ビュー (過去 30 日間)
Skyx
Skyx 2018 年 7 月 7 日
コメント済み: Skyx 2018 年 7 月 7 日
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.

採用された回答

Stephen23
Stephen23 2018 年 7 月 7 日
編集済み: Stephen23 2018 年 7 月 7 日
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 件のコメント
Image Analyst
Image Analyst 2018 年 7 月 7 日
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 2018 年 7 月 7 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by