Returning the final value of a while loop

I have a problem where I need to run a loop until x-y is less than a certain amount, with x getting smaller every time. When x-y is finally less than, say, h, how can I return the final value of x and put it into a variable? This is part of a larger function, and I don't want it to just display, I need to store the x value in a variable. For example:
function P = (x,y,h)
while (x-y) > h
x=x-1;
end
end
how can I make the answer to the function equal to the final x value?

 채택된 답변

James Tursa
James Tursa 2015년 3월 10일
편집: James Tursa 2015년 3월 10일

0 개 추천

Just set your return variable to x. E.g.,
function P = myFunction(x,y,h)
while (x-y) > h
x=x-1;
end
P = x;
end
Note: There are better ways to get the final x value that don't involve brute force subtracting 1 in a loop.

댓글 수: 1

chazz
chazz 2015년 3월 10일
편집: chazz 2015년 3월 10일
Duh...well I guess trying to make it simpler didn't really help me, the code below is really what I'm trying to solve. I need to return the last integral of the while loop, the one that is small enough to satisfy the inequality. How can I do that?
function q = myimproperintegral(f,a,b,tol)
syms x;
k = 2;
H=0;
before = int(f(x),(a+(b-a)/k),b);
after = int(f(x),(a + (b-a)/(k+1)),b);
while before-after > tol
k=k+1;
H=int(f(x),(a+(b-a)/(k+1)),b);
end
q=double(H)
end

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2015년 3월 10일

편집:

2015년 3월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by