Sum of a list of numbers if they're a certain value or not

27 ビュー (過去 30 日間)
Daniel
Daniel 2011 年 12 月 4 日
I have a list of numbers, and I'm trying to determine the sum of all of the numbers that have a value less than 55. I know that this will involve some sort of logic set-up, but I'm not familiar with how to set it up exactly. Any help is really appreciated.

採用された回答

bym
bym 2011 年 12 月 4 日
Or even (without using sum)
x.'*(x<55)
[edit]
for x being a matrix
x = randi(100,20,20);
sx = x(:).'*(x(:)<55);
  4 件のコメント
Daniel
Daniel 2011 年 12 月 5 日
Thank you! Worked like a charm. Can you explain what the code is doing though? I really appreciate it.
bym
bym 2011 年 12 月 5 日
reading from left to right the line x(:).'*(x(:)<55);
x(:) returns all elements of x in a column (see doc colon)
.' transposes x(:)from column to row
* is matrix multiply
(x(:)<55) returns a column of 1's & 0's (1 is true x(n),55)
in summary, you are transforming the matrix in to 1 row and matrix multiplying it by a column of boolean values generated by the logical test. The addition is implicit in the matrix multiply

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

その他の回答 (2 件)

bym
bym 2011 年 12 月 4 日
x=randi(100,20,1);
sx = sum(x(x<=55))
  2 件のコメント
Daniel
Daniel 2011 年 12 月 4 日
This didn't work. Should I mention that the list of numbers are in matrix form?
Walter Roberson
Walter Roberson 2011 年 12 月 4 日
sx = sum(x(x(:) <= 55));

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


Walter Roberson
Walter Roberson 2011 年 12 月 4 日
Alternatives:
sum(x .* (x <= 55))
or
sum(x(find(x<=55)))
  8 件のコメント
Image Analyst
Image Analyst 2011 年 12 月 5 日
No, that's not it. It works just fine with <=. I just changed it to less than because that's what you said. But <= will also work fine - just try it. There must have been some other reason that you're not telling us and we don't know because you didn't share your code.
Jan
Jan 2011 年 12 月 6 日
@Walter: What about logical indexing? FIND is not useful here:
sum(x(x<=55))

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by