delete the row where is a NaN

1 回表示 (過去 30 日間)
Saad
Saad 2013 年 1 月 14 日
Dear all,
I am stuck in a silly programming problem and I would like to ask for some help please.
I have two cells a and b:
a=num2cell(1:10); b=num2cell(1:10);
in each cell, I have 10 column vectors (n x 1). The cell "a" has a NaN that I would like to delete. I also would like to multiply the matrices in each cell. However if I delete some row in a{i} then the matrix size will change so I have to delete the same row in b{i} so that the matrices a{i} and b{i} have the same size. To illustrate what I am trying to achieve, here the structure of my code:
for i=1:10
if a{i}(isnan(a{i}))
%% complete here
end
a{i}'*b{i};
end
I would greatly appreciate if you could help me complete the code. Basically I would like to tell the code "if there is a NaN in a{i}, please delete the row, and show me the row number. Then I will delete the same row in b{i} and finally multiply a{i} and b{i}.
Thanks a lot
Kind Regards
S

採用された回答

Matt J
Matt J 2013 年 1 月 14 日
編集済み: Matt J 2013 年 1 月 14 日
Looping will be faster than proposals based on cellfun or arrayfun
for i=1:10
badrows=any(isnan(a{i}),2);
a{i}(badrows,:)=[];
b{i}(badrows,:)=[];
a{i}'*b{i};
end
  1 件のコメント
Saad
Saad 2013 年 1 月 14 日
Matt
Thanks a lot Matt. Your code was the simplest to understand.

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

その他の回答 (2 件)

Shashank Prasanna
Shashank Prasanna 2013 年 1 月 14 日
編集済み: Shashank Prasanna 2013 年 1 月 14 日
Is there a requirement to be using cells? if no you can do this quickly without loops, if yes, you can always convert them into cells after you are done.
Let
a = [1 2 nan 4 6 7 nan 7 3 nan 10]
b = [1 2 3 4 6 7 7 7 3 7 10]
b(isnan(a))=[]
a(isnan(a))=[]
c = a.*b
% If you would like:
c = num2cell(c)
  1 件のコメント
Saad
Saad 2013 年 1 月 14 日
Thank you your help SP.

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


Azzi Abdelmalek
Azzi Abdelmalek 2013 年 1 月 14 日
% ------Your data-------------
n=4
a1=randi(9,n,10);
b1=randi(9,n,10);
a1( randperm(10*n,10))=nan
a=num2cell(a1)
b=num2cell(b1)
% ------the code---------------
aa=cell2mat(a);
bb=cell2mat(b);
idx=~cellfun(@isnan,a)
out=arrayfun(@(x) aa(idx(:,x)).*bb(idx(:,x)),1:size(aa,2),'un',0)
  1 件のコメント
Saad
Saad 2013 年 1 月 14 日
Thank you Azzi.

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

カテゴリ

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