Can I loop through arguments and loop back to original names
이전 댓글 표시
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
Dyuman Joshi
2023년 6월 30일
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
2023년 6월 30일
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!