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 Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2018b

질문:

2018년 12월 6일

댓글:

2018년 12월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by