How to create a meaningful loop to meet certain conditions

1 回表示 (過去 30 日間)
Mirko Mißbach
Mirko Mißbach 2020 年 12 月 2 日
コメント済み: Ameer Hamza 2020 年 12 月 2 日
Hi there,
I want to create a loop function that sets the value of xA according to a vector A = linspace(100,150,51). Respecting the current value of xA, xB shall be used for computation along a certian delta, like (300 <= xB <=350) and with a step size of 1. By the way, xA and xB are just scalars.
After xA and xB are defined, a set of equations is solved. Then, the results of these solved equations are compared to each other. If all results are equal within a tolerance, the loop is ended and the respecting values of xA and xB are displayed. If the results are not equal (within tolerance) the values of xA and xB are changed as described above.
If I had any idea how to solve this I would show you my code - but since I am newbie, it would make no sence to present something.
Thanks a lot for any helpful comment!!!

回答 (1 件)

Ameer Hamza
Ameer Hamza 2020 年 12 月 2 日
Something like this perhaps,
A = 100:1:150; % for fixed spacing, this syntax is more readable
B = 300:1:350;
for i = 1:numel(A)
xA = A(i);
for j = 1:numel(B)
xB = B(j);
% solve the equation here
if abs(sol1-sol2)<1e-6 % compare two numbers with tolerance
fprintf('Solution is xA=%.f and xB=%f\n.', xA, xB);
break; % break the loop
end
end
end
  4 件のコメント
Mirko Mißbach
Mirko Mißbach 2020 年 12 月 2 日
Thank you, both variants work. Unfortunatelly I have just identified another problem which forces me to incorporate a further "requirement".
Within the range of A and B there are solutions with positive and negative values for sol1 sol2 and sol3 (like: sol1 < 0; sol2 > 0 and sol3 < 0 ...). But there is at least one solution in which sol1 sol2 and sol3 are all positive or all negative! How can I smartly incorporate this requirement right before equality check?
Thanks again for helpful comments :)
Ameer Hamza
Ameer Hamza 2020 年 12 月 2 日
If you want to make sure that three numbers have same sign, you can try something like this
all(diff(sign(x))==0)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by