How to use 'for loop' to check user input?
Mostrar comentarios más antiguos
I am trying to ask a user to input a value between 0-1. I then want to check that value against pre-existing variables r1b, r2b, r3b to see if it is greater and output the corresponding column as disp. So if user enters 0.15, it will be greater than r2b and r3b and the return will be columns r2a and r3a.
I have code to display the dialog box and return an error if not correct, but am not sure how to incorporate the loop?
r1a= column
r2a= colum
r3a= column
r1b=0.1
r2b=0.2
r3b=0.3
exit=false;
msg='Please enter an R^2 value for Cement:';
while ~exit
data = str2double( inputdlg(msg) );
exit = (0<= data1 && 1>=data1);
if ~exit
msg = 'Input must be between the values 0-1. Please re-enter: ';
end
end
Respuesta aceptada
Más respuestas (1)
modify the upper limit in exit condition line according to the user input,
x = [ 1 2 3
1 2 3
1 2 3];
r1a = x(:,1);
r2a = x(:,2);
r3a = x(:,3);
r1b = 3;
r2b = 6;
r3b = 9;
exit = false;
msg = 'Please enter an R^2 value for Cement:'
if ~exit
data = str2double('5') % // e.g. user input
exit = (0 <= data && 10 >= data) % modify the upper limit in line according the user input
if ~exit
msg = 'Input must be between the values 0-1. Please re-enter: ';
end
if data > r1b & (data < r2b | data < r3b)
disp([r2a r3a])
elseif data > r2b & (data < r1b | data < r3b)
disp([r1a r3a])
elseif data > r3b & (data < r1b | data < r2b)
disp([r1a r2a])
end
end
1 comentario
you might want to add more conditions if the user input is less than all other values in conditions , in which case it need to prompt user for required output. Here i have used if-else conditional statement to demonstrate, since using a while loop it will never exit the loop, so its better to include a condition to exit the loop when the user inputs / outputs are all satisfied. Preferabl, a break statement with a condition inside the loop is necessary to exit the loop
x = [ 1 2 3
1 2 3
1 2 3];
r1a = x(:,1);
r2a = x(:,2);
r3a = x(:,3);
r1b = 0.1;
r2b = 0.2;
r3b = 0.3;
exit = false;
msg = 'Please enter an R^2 value for Cement:'
if ~exit
data = str2double('0.15') % // e.g. user input
exit = (0 <= data & 1 >= data) % modify the upper limit in line according the user input
if ~exit
msg = 'Input must be between the values 0-1. Please re-enter: ';
end
if data > r1b & (data > r2b & data > r3b)
disp('Specify the output required')
elseif data > r1b & (data < r2b & data < r3b)
disp([r2a r3a])
elseif data > r2b & (data < r1b & data < r3b)
disp([r1a r3a])
elseif data > r3b & (data < r1b & data < r2b)
disp([r1a r2a])
end
end
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!