필터 지우기
필터 지우기

Getting number of variables whose sum is lower than certain number

조회 수: 4 (최근 30일)
Banjo
Banjo 2017년 12월 9일
댓글: Star Strider 2017년 12월 10일
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!

채택된 답변

Star Strider
Star Strider 2017년 12월 9일
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
Banjo
Banjo 2017년 12월 10일
편집: Banjo 2017년 12월 10일
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 2017년 12월 10일
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.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by