globloopprompt = 'Input value for Alpha :';
alpha = input(prompt);
if (alpha>=0.01 && alpha<=0.2)
global alpha;
else
error ('Incorrect alpha value');
end
I am new to matlab. Ive created this function and t all works with my corisponding code.
how would i make this code prompt the user to input another value for alpha, if they original enter a value for alpha outside the perameters.
Thank you in advance.

 採用された回答

madhan ravi
madhan ravi 2018 年 12 月 6 日
編集済み: madhan ravi 2018 年 12 月 6 日

0 投票

EDITED
Avoid using global , how about the below?:
Save the below as a function with the name inputalpha.m and just call this function in the script.
function alpha = inputalpha
prompt = 'Input value for Alpha :';
alpha = input(prompt);
if (alpha>=0.01 && alpha<=0.2)
alpha=alpha;
else
disp('Incorrect alpha value not within bounds');
prompt = 'Input value for Alpha :';
alpha = input(prompt);
end
end

6 件のコメント

vinesh vegad
vinesh vegad 2018 年 12 月 6 日
thank you.
the reason i had the global was because the alpha value that gets inputted by the user is solved on another function m-file.
is there a way of having this as well as the global intergrated into this.
thank you
Rik
Rik 2018 年 12 月 6 日
You can further improve upon this function by making it recursive:
function alpha = inputalpha
prompt = 'Input value for Alpha :';
alpha = input(prompt);
a_lo=0.01;a_hi=0.2;%set bounds
if ~(alpha>=a_lo && alpha<=a_hi)
clc
fprintf('Incorrect alpha value: not within bounds\n');
fprintf('Alpha value should be between %.2f and %.2f\n',a_lo,a_hi);
alpha = inputalpha;%recursive call
end
end
madhan ravi
madhan ravi 2018 年 12 月 6 日
Thank you very much Rik , I think clc can be avoided because it may erase the previously calculated values from the script but then it depends upon the OP's wish though.
vinesh vegad
vinesh vegad 2018 年 12 月 6 日
thank you both for the help
Rik
Rik 2018 年 12 月 6 日
The clc is indeed a matter of context and taste. You can expand this even further by making the bounds optional input arguments:
function alpha = inputalpha(a_lo,a_hi)
prompt = 'Input value for Alpha :';
alpha = input(prompt);
if nargin~=2
a_lo=0.01;a_hi=0.2;%set bounds
end
if ~(alpha>=a_lo && alpha<=a_hi)
clc
fprintf('Incorrect alpha value: not within bounds\n');
fprintf('Alpha value should be between %.2f and %.2f\n',a_lo,a_hi);
alpha = inputalpha(a_lo,a_hi);%recursive call
end
end
madhan ravi
madhan ravi 2018 年 12 月 6 日
Anytime :) @Vinesh , if the answer helped make sure to accept the answer and once again thank you very much at Rik ;-)

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および 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