Filter löschen
Filter löschen

HELP! Checking if variable increases after each iteration is completed

5 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 9 Mär. 2019
y = y - sign(y) * 0.001;

Weitere Antworten (1)

John D'Errico
John D'Errico am 9 Mär. 2019
Bearbeitet: John D'Errico am 9 Mär. 2019
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 Kommentar
Hawki005
Hawki005 am 9 Mär. 2019
Bearbeitet: Hawki005 am 9 Mär. 2019
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!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by