If loop on lists for counting elements

3 ビュー (過去 30 日間)
Gorbz
Gorbz 2021 年 8 月 5 日
回答済み: KSSV 2021 年 8 月 5 日
I have two lists
A0 = [1,3,5,9];
A1 = [2,5,1,0];
and I want to make counts of how many elements in A0 are smaller than A1. I define:
counter0 = 0;
counter1 = 0;
and then the for loop:
for k=1:length(A0)
if A0(k)>A1(k)
counter0 = counter0 + 1
else if A0(k)<A1(k)
counter1 = counter1 + 1
end
end
end
So the result should had been:
counter0 = 2
counter1 = 2
But this loop will not work for me. How can I make it functional?

回答 (3 件)

Awais Saeed
Awais Saeed 2021 年 8 月 5 日
You do not need a loop for this, just use
A0 = [1,3,5,9];
A1 = [2,5,1,0];
count = length(find(A0<A1))

KSSV
KSSV 2021 年 8 月 5 日
A0 = [1,3,5,9];
A1 = [2,5,1,0];
iwant = 0 ;
for i = 1:length(A0)
t = nnz(A0(i)<A1) ;
iwant = iwant+t ;
end

KSSV
KSSV 2021 年 8 月 5 日
A0 = [1,3,5,9];
A1 = [2,5,1,0];
idx = A0' < A1 ;
iwant = nnz(idx(:)) ;

カテゴリ

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