Why does an array have a different column dimension than the array used to define that array?

1 回表示 (過去 30 日間)
I enclose a m file and a small data file. A is a column array with dimension 3233 by 1. B is a column array defined using A and its dimension should stay the same. It does not. It has dimension 3232 by 1. In particular, the very last element gets lost in B. What is going on?

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 1 月 23 日
You have defined B directly from a logical condition. When you do so, MATLAB checks for logical true values and defines accordingly; so the resulting variable is updated till the last logical true value.
Which is the 3232nd value here -
A=load('data.mat').A;
idx=find(A==2,1,'last')
idx = 3232
%Example
x=1:10;
%size of y is not same as size of x
y(x<7)=0
y = 1×6
0 0 0 0 0 0
To get the desired result, you should pre-allocate B with the same size as A and then apply the condition.
B=zeros(size(A));
B(A==2)=1;
size(B)
ans = 1×2
3233 1
Also, you should consider what values those B elements take where elements of A are not equalto 2.
  2 件のコメント
Snoopy
Snoopy 2023 年 1 月 23 日
Clear. Thanks, also to the other answer by Stephen23. I did not know which one to accept so I did randomly.
Stephen23
Stephen23 2023 年 1 月 23 日
Simpler way to get the vector B:
B = A==2;

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by