If loop on lists for counting elements

2 views (last 30 days)
Gorbz
Gorbz on 5 Aug 2021
Answered: KSSV on 5 Aug 2021
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;
andthen the for loop:
fork=1:length(A0)
ifA0(k)>A1(k)
counter0 = counter0 + 1
else ifA0(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?

Answers (3)

Awais Saeed
Awais Saeed on 5 Aug 2021
You do not need a loop for this, just use
A0 = [1,3,5,9];
A1 = [2,5,1,0];
count = length(find(A0

KSSV
KSSV on 5 Aug 2021
A0 = [1,3,5,9];
A1 = [2,5,1,0];
iwant = 0 ;
fori = 1:length(A0)
t = nnz(A0(i)
iwant = iwant+t ;
end

KSSV
KSSV on 5 Aug 2021
A0 = [1,3,5,9];
A1 = [2,5,1,0];
idx = A0' < A1 ;
iwant = nnz(idx(:)) ;

s manbetx 845

Community Treasure Hunt

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

Start Hunting!