How to sum all instances of a value across a variable?

조회 수: 1 (최근 30일)
Louisa Thomas
Louisa Thomas 2018년 1월 15일
댓글: Louisa Thomas 2018년 1월 15일
My variable follows this format
a = [1 2 2 1]
etc.
So all of the values are either 1, or 2.
How do I sum all of the instances of the number 1 across this variable?
  댓글 수: 1
Jan
Jan 2018년 1월 15일
Is this a homework question? If so, what have you tried so far? Do you want to solve it with a loop or with the efficient builtin method unique and histcounts?
As usual I could offer a method based on RunLength. After I have suggested it a hundred of times in the forum already, I think about changing my nick name to "JanLength".

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

채택된 답변

Jan
Jan 2018년 1월 15일
편집: Jan 2018년 1월 15일
a = [1 2 2 1]
k = 1;
sumOf1 = sum(a(a == k))
or
sumOf1 = k * sum(a == k)
But maybe you want to get the result for all elements of a? Then please explain this. unique and histcounts will be useful.
  댓글 수: 1
Louisa Thomas
Louisa Thomas 2018년 1월 15일
The first part was great thank you. It worked perfectly! It's part of a data extraction script, so I just worked with that format, and it worked :)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by