필터 지우기
필터 지우기

HELP! Checking if variable increases after each iteration is completed

조회 수: 5 (최근 30일)
I have a piece of code that uses an assumed value of x = 1 for the first iteration. The code then calculates a value of (y). For the best accuracy of (y), succesive iterations continue until (x) is less than 0.00001 for example.
This issue im having is that depending on other conditions, (y) can be positive or negative. To converge to zero, on each iteration, if (y) is positive then 0.001 must be subtracted. If (y) is calculated to be negative, 0.001 must be added to converge to zero.
I need some way of itentifying if (y) is postive or negative on each iteration, and then add or subract a small value to (y) before the next iteration starts depending if (y) is positive or negative.
Any help would be greatly appreciated! Thanks in advance.

채택된 답변

Walter Roberson
Walter Roberson 2019년 3월 9일
y = y - sign(y) * 0.001;

추가 답변 (1개)

John D'Errico
John D'Errico 2019년 3월 9일
편집: John D'Errico 2019년 3월 9일
Surely there are many things you can do, and your question is very confusing. Perhaps this?
if abs(y) < 0.001
stuff
end
It is not clear what you are doing, but why would this not work?
if y < 0
% stuff for y < 0
elseif y > 0
% stuff for y > 0
else
disp('Y is zero!!!!!!!')
load handel
sound(y,Fs)
end
Solving a problem by perturbing a variable in steps of 0.001 seems like a poor programming style, but if it floats your boat, then break out the paddles and be happy. I'd instead suggest you might consider learnign about tools like fzero as a good way to improve your code in the future.
  댓글 수: 1
Hawki005
Hawki005 2019년 3월 9일
편집: Hawki005 2019년 3월 9일
Sorry for the confusion.
My problem is that y can be postive or negative, but...
If y is positive, and getting more positive after each iteration, I need to subtract to make it smaller and converge to zero.
If y is negative and getting more negative, I need to add to make it converge to zero.
I think the confusing thing is that y is calculated, x checks the diffrence between another way of calculating y. And then the original y is reused in the next iteration cycle until x is almost zero .
Thank you for your quick reply!

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

카테고리

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

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by