Getting number of variables whose sum is lower than certain number

5 views (last 30 days)
Hi all,
I have a problem because I don't know how to get the number of X's whose sum is lower than number N. Condition that must be fulfilled is that loop should repeat until the sum of X's reaches or exceeds number N. In case the sum exceeds number N, *it should give me 'There are 3 numbers X.' which is 25, 36 and 16. Number 49 should not be taken into consideration since when it is included in the sum (126) it exceeds number N (100).*
Here is my try but obviously there should be something more:
N=100;
r=[5 6 4 7 3 2];
s=0;
for i=1:1:length(r)
X=r(i).^2;
sprintf('X = %.1f',X)
s=s+X;
if (s > N || s == N)
break
end
end
sprintf('Sum = %.1f',s)
sprintf('There are %d numbers X.'length(X))
Output
ans =
X = 25.0
ans =
X = 36.0
ans =
X = 16.0
ans =
X = 49.0
ans =
Sum = 126.0
ans =
There are 1 numbers X.
I hope I explained as clearer as possible. Thank you for your help!

Accepted Answer

Star Strider
Star Strider on 9 Dec 2017
Your for loop increments the counter until you exit it, so ‘i’ tracks the quantity of numbers you used to complete the loop.
Try this:
sprintf('There are %d numbers X.', i)
  8 Comments
Banjo
Banjo on 10 Dec 2017
Edited: Banjo on 10 Dec 2017
Hello, I managed to get sum of 82 which is ok. Number 96 was just an example, not a real number.
I was wondering if it is possible to use two for loops, one for X and one for Y since I want to get how many X's and Y's are included in the sum. For the code above it should be 'There are 2 numbers X.' and 'There are 2 numbers Y'. Thanks!
Star Strider
Star Strider on 10 Dec 2017
My pleasure.
If I remember correctly, that’s what I got as well.
A double loop would likely be overkill. You could put in a separate counter for ‘Y’, however since you are summing each of them, adding the sums, and then using that sum as your exit criterion, the counters for both would be the same. (There is no condition on calculating ‘Y’ that depends on ‘X’, ‘s’, ‘m’, or ‘k’, so the same single iteration counter ‘i’ applies to all of them.)
I would just leave it as is, unless you also want to add a separate fprintf statement for ‘Y’, using the same counter.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!