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

27 次查看(过去 30 天)
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))

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 CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by