how to create an input loop?

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.

 Risposta accettata

madhan ravi
madhan ravi il 6 Dic 2018
Modificato: madhan ravi il 6 Dic 2018
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 Commenti

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
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 il 6 Dic 2018
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.
thank you both for the help
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 il 6 Dic 2018
Anytime :) @Vinesh , if the answer helped make sure to accept the answer and once again thank you very much at Rik ;-)

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Prodotti

Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by