필터 지우기
필터 지우기

How to count in arrays?

조회 수: 2 (최근 30일)
Evelyn
Evelyn 2014년 11월 17일
댓글: John D'Errico 2014년 11월 17일
Let's say I have two arrays
apple = [1 2 3 4 5 6 7 8];
pear = [2 3 1 2 7 6 1 8];
I want to compare these arrays and count how many items in pear are bigger than the item at the same place in apple. How would I do this?
  댓글 수: 1
the cyclist
the cyclist 2014년 11월 17일
편집: the cyclist 2014년 11월 17일
Sounds like homework. Here are a few hints:
  • There is "greater than" operator in MATLAB, which will operate on vectors
  • There is also an operator that will sum over a vector
  • There is a docsearch command that will search the documentation

댓글을 달려면 로그인하십시오.

채택된 답변

Manoj
Manoj 2014년 11월 17일
x=sum(pear>apple);
  댓글 수: 1
John D'Errico
John D'Errico 2014년 11월 17일
While this correct, I recall that it will be slightly faster to use nnz instead of sum.
x = nnz(pear > apple);
The difference will be small unless the arrays are significantly large.
pear = round(rand(1,1e7)*10);
apple = round(rand(1,1e7)*10);
timeit(@() sum(pear > apple))
ans =
0.03888
timeit(@() nnz(pear > apple))
ans =
0.023221

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by