フィルターのクリア

About the end used in vector append

1 回表示 (過去 30 日間)
Gary Bikini
Gary Bikini 2021 年 2 月 1 日
コメント済み: Gary Bikini 2021 年 2 月 2 日
% run the following code, there will be wrong
% I wanna know why
a=[];
a(end+1:2)=[8,9];
a(end+1:2)=[8,9]; % wrong, why

採用された回答

Steven Lord
Steven Lord 2021 年 2 月 1 日
% run the following code, there will be wrong
% I wanna know why
a=[];
a(end+1:2)=[8,9]
a = 1×2
8 9
% a(end+1:2)=[8,9] % wrong, why
I've commented out that third line of code so the three lines later in this post can execute. The error message it throws is "Unable to perform assignment because the left and right sides have a different number of elements."
When you run the third line of code, a has 2 elements and so the linear end of a is element 2. This makes end+1 equal to 3 and the section of a that goes from element 3 to element 2 in steps of 1 is empty. You can't store two elements on the right into no elements on the left. [MATLAB performs the addition before calling colon based on the operator precedence table.]
If instead you want to perform the colon first, use parentheses to force it to go first.
b = [];
b(end+(1:2)) = [8 9]
b = 1×2
8 9
b(end+(1:2)) = [0 1]
b = 1×4
8 9 0 1
In the third line in this code, the linear end of b is element 2, and 2+(1:2) is the vector [3 4]. You can assign two elements (on the right) to two elements (on the left.)
  1 件のコメント
Gary Bikini
Gary Bikini 2021 年 2 月 2 日
It's great. Thanks!

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

その他の回答 (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