Sum of a list of numbers if they're a certain value or not
Mostra commenti meno recenti
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.
Risposta accettata
Più risposte (2)
bym
il 4 Dic 2011
x=randi(100,20,1);
sx = sum(x(x<=55))
Walter Roberson
il 4 Dic 2011
Alternatives:
sum(x .* (x <= 55))
or
sum(x(find(x<=55)))
8 Commenti
Daniel
il 4 Dic 2011
Walter Roberson
il 4 Dic 2011
What error did it give, and for which version?
The first one should have worked on an array, but would have given column sums. The second one should just plain have worked.
Question 1: is your matrix perhaps symbolic values? You cannot compare symbolic values to a number.
Question 2: is your matrix perhaps an odd data type such as a MATLAB object? Or is it perhaps int64() and you do not have a R2011 MATLAB ?
Image Analyst
il 4 Dic 2011
I don't have the Mind Reading Toolbox. What's your error and can you give some sample code to generate your array that will illustrate your error? Also, do you want what your title says (equal to a certain value) or what the subject body says (less than a certain value)? Please clarify since you're being ambiguous.
Daniel
il 5 Dic 2011
Image Analyst
il 5 Dic 2011
That doesn't make sense. I ran this and it worked just fine:
x = randi(100,20,20);
s1=sum(x(x < 55))
s2=sum(x(find(x < 55)))
Both s1 and s2 gave the same value (meaning you don't need the find() function). I got no error whatsoever. Run the code I gave and tell me if that works fine. If it does, then try to see what is different about your code. Make sure you didn't use x one time and X another time - MATLAB is case sensitive.
Daniel
il 5 Dic 2011
Image Analyst
il 5 Dic 2011
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
il 6 Dic 2011
@Walter: What about logical indexing? FIND is not useful here:
sum(x(x<=55))
Categorie
Scopri di più su Logical in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!