How to terminate an if-elseif-else statement once a condition is met.

37 ビュー (過去 30 日間)
Gideon Idumah
Gideon Idumah 2018 年 11 月 11 日
コメント済み: Gideon Idumah 2018 年 11 月 14 日
I want a situation whereby if the first 'if' statement is true (norm_sn <= del), the code should calculate x_plus and exit the if condition (jump to calculate f_x), or if the 'if' statement is false and the 'elseif' statement is true (del <= norm_s_cp), the code should calculate x_plus and exit the if statements (jump to calculate f_x). if none of the first two is true, then it can calculate the 'else'. I want it to be in that order. Can someone help me out. Thank you.
function [x_plus,grad,norm_grad,f_x,f_xplus,m_xplus] = dogleg(f,x,del)
syms x_1 x_2 aux
grad = subs(gradient(f,[x_1,x_2]),[x_1,x_2],x');
norm_grad = norm(grad);
H = subs(hessian(f,[x_1,x_2]),[x_1,x_2],x');
%
s_n = -H^-1*grad; norm_sn = norm(s_n);
lambda_star1 = norm_grad^2/(grad'*H*grad);
s_cp = -lambda_star1*grad; norm_s_cp = norm(s_cp);
if norm_sn <= del
x_plus = x + s_n;
elseif del <= norm_s_cp
x_plus = x - (del/norm_grad)*grad;
else
gamma = norm_grad^4/((grad'*H*grad)*(grad'*abs(s_n)));
%gamma = norm_s_cp*norm(grad)/grad'*abs(s_n);
eta = 0.8*gamma + 0.2;
s_ncap = eta*s_n;
lambda = solve(norm(s_cp + aux*(s_ncap - s_cp))^2 == del^2);
x_plus = x + s_cp + lambda(lambda>0)*(s_ncap - s_cp);
end
f_x = subs(f,[x_1,x_2],x');
f_xplus = subs(f,[x_1,x_2],x_plus');
m_xplus = f_x + grad'*(x_plus - x) + 0.5*(x_plus - x)'*H*(x_plus - x);
end
  4 件のコメント
Walter Roberson
Walter Roberson 2018 年 11 月 11 日
That already happens for numeric values. And you do not have a loop.
However without knowing the f, we cannot tell whether the norm is certain to be convertible to numeric. If the norm turns out to involve symbolic variables then the comparison could invoke an error.
Rik
Rik 2018 年 11 月 11 日
if...elseif...else...end is not a loop. If you want something to happen under some condition, make sure you have that as a test. See the example below for what happens when conditions overlap.
cond1=true;cond2=true;
if cond1 && cond2
disp(1)
elseif cond1
disp(2)
elseif cond2
disp(3)
else
disp(4)
end

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

採用された回答

Image Analyst
Image Analyst 2018 年 11 月 12 日
I don't see a loop but if there were, you could put a "break" statement there. As it is, you can put a "return" statement wherever you want to exit the function immediately, as long as all the output variables have been assigned.
  1 件のコメント
Gideon Idumah
Gideon Idumah 2018 年 11 月 14 日
Thank you.
I just created a new function, and put a return at the end of the "if" and "elseif" statement.

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

その他の回答 (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