フィルターのクリア

HELP! Checking if variable increases after each iteration is completed

5 ビュー (過去 30 日間)
Hawki005
Hawki005 2019 年 3 月 9 日
コメント済み: Hawki005 2019 年 3 月 11 日
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 Center および File ExchangeLoops 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