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.

 Respuesta aceptada

madhan ravi
madhan ravi el 6 de Dic. de 2018
Editada: madhan ravi el 6 de Dic. de 2018

0 votos

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 comentarios

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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Productos

Versión

R2018b

Preguntada:

el 6 de Dic. de 2018

Comentada:

el 6 de Dic. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by