How to make a loop through each row?

1 回表示 (過去 30 日間)
Daria Ivanchenko
Daria Ivanchenko 2020 年 10 月 21 日
コメント済み: David Hill 2020 年 10 月 21 日
Hi! I have a variable A in the size of 50x15000 with different numbers. And I have variable B, the same size 50x15000, that has only zeros and ones. I want to filter the data in the variable A based on variable B, and put the result in variable C. I need to take the numbers from A only if it is zero in the matrix B. One row is one trial in both A and B.
I wrote a small for loop:
C = NaN(size(A));
for i = 1:size(A,1)
C(i,:) = A(i, B(i,:) == 0);
end
The problem is that, after filtering the data, each row has different number of columns, so it doesn't want to be in one matrix. I have a message like this: "Unable to perform assignment because the size of the left side is 1-by-15000 and the size of the right side is 1-by-13683".
How can I solve this problem?
Thank you!
  2 件のコメント
Stephen23
Stephen23 2020 年 10 月 21 日
"How can I solve this problem?"
Which would you prefer?:
  • a matrix padded with NaN (or some other value).
  • a container array (e.g. cell array) of vectors.
Daria Ivanchenko
Daria Ivanchenko 2020 年 10 月 21 日
A matrix padded with NaN would be better!

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

回答 (1 件)

David Hill
David Hill 2020 年 10 月 21 日
編集済み: David Hill 2020 年 10 月 21 日
Make C a cell array
for i = 1:size(A,1)
C{i} = A(i, B(i,:) == 0);
end
  2 件のコメント
Daria Ivanchenko
Daria Ivanchenko 2020 年 10 月 21 日
Yes, this works, thanks, but it is really necessary for me to have all in one matrix and not in differents cells.
David Hill
David Hill 2020 年 10 月 21 日
C=zeros(size(A));
C(B==0)=A(B==0);
C(B==1)=nan;

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by