Can I loop through arguments and loop back to original names
Mostrar comentarios más antiguos
I have a function that can take in a value to check and a min value and max value to validate if the value to check is in range. The function though also error handles if any of the arguments come in from a input('prompt', 's') function.
So I have the following which works:
function [isValid, errorMessage] = validateNumberWithRange(value, min, max)
...
inputs = {value, min, max};
for i = 1:numel(inputs)
if ~isnumeric(inputs{i})
inputs{i} = str2double(inputs{i});
if isnan(inputs{i})
errorMessage = "All values must be numeric, please check your inputs.";
isValid = false;
end
end
end
end
The problem is let's say value = '500'
The loop will make inputs{1} = 500 without the single quotes and be numeric but at the end of the loop value is still '500' so I have to do one of the following:
Version 1:
value = inputs{1};
min = inputs{2};
max = inputs{3};
if value < min || value > max
errorMessage = "The Value is not within range, please check your inputs.";
isValid = false;
end
Version 2:
if inputs{1} < inputs{2} || inputs{1} > inputs{3}
errorMessage = "The Value is not within range, please check your inputs.";
isValid = false;
end
Both ways work, but already just don't feel right to me and could get even uglier if there were more arguments.
Is there a way to in the loop or with another loop, get any type conversions that had to be done through inputs{} back to their original variable names?
2 comentarios
Dyuman Joshi
el 30 de Jun. de 2023
If you have the Symbolic Math Toolbox, you can also use sym and then compare. (Symbolic values are represented in their exact form, while double values have a limited precision)
Matthew
el 30 de Jun. de 2023
Respuesta aceptada
Más respuestas (0)
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!