フィルターのクリア

count of non zero elements of a row vector in a loop

3 ビュー (過去 30 日間)
Georgios Kirkinezos
Georgios Kirkinezos 2020 年 10 月 28 日
コメント済み: Peter O 2020 年 10 月 28 日
Hi everyone,
i want to count the nonzero elements of a row-vector in a loop, i have the initial (360,1000) matrix u_new
for i=1:360;
for j=1:1000;
if u_new(i,j)==0 %%% here i transformed zeros to Nan, to use the following command isnan
u_new(i,j)=NaN;
insample_u_new=isnan(u_new(i,:))==0; %%% in this row-vector the possible values are 0 or 1, i am interested in getting the number of ones
P = numel(insample_u_new(i,j)~= 0); %%%here is the problem
end
end
end
I want the output P to be the number of the nonzero elements (ones) from the row-vector u_new=u(:,1:1000) for the loop.
Thanks for your answers in advance.

採用された回答

Peter O
Peter O 2020 年 10 月 28 日
Try the nnz function.
It sounds like you're trying to count the number of nonzero elements in each row? Use arrayfun to apply this function to each row of the matrix (extracting the row index).
NZ = arrayfun(@(ix) nnz(u_new(ix,:)),1:size(u_new,1))
NZ will be a 1 x n_rows vector containing the nonzero element counts for each row.
  2 件のコメント
Georgios Kirkinezos
Georgios Kirkinezos 2020 年 10 月 28 日
I used the following command and it worked for my code based on nnz as you mentioned
NZ(i) = nnz(insample_u_new);
Peter O
Peter O 2020 年 10 月 28 日
Glad to hear it worked for your use!

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

その他の回答 (1 件)

KSSV
KSSV 2020 年 10 月 28 日
Read about nnz.

カテゴリ

Help Center および File ExchangeDenoising and Compression についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by