Setting variable names inside function based on input arguement in MATLAB
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Richard Cheung
le 2 Avr 2020
Commenté : Richard Cheung
le 2 Avr 2020
I have code that looks like this:
str = '';
x = NaN;
while isnan(x)
x = str2double(input([str, 'Enter a value for x: '], 's'));
str = 'Please enter a number. ';
end
str = '';
y = NaN;
while isnan(y)
y = str2double(input([str, 'Enter a value for y: '], 's'));
str = 'Please enter a number. ';
end
The two blocks are identical in use and the only difference is that one uses x as the variable name whilst the other uses y as the variable name.
I was wondering if there was a way to create a function which is able to take in the variable name as its input arguement and be able to set the variable names inside that function as well as what is displayed in terms of the input arguement.
Something like:
x = testNum(x); % Error using testNum; Too many output arguments.
y = testNum(y);
z = x + y;
fprintf("Sum is %d", z)
function testNum(~)
str = '';
val = NaN;
while isnan(val)
val = str2double(input([str, 'Enter a value for %s: '], 's')); % Not sure how to get variable name to appear in this format
str = 'Please enter a number. ';
end
end
A few problems I have with this is that there are too many output arguements for when I'm initialising x and y. Another thing is that I'm not sure on the formatting of text when using an array for input.
Essentially, I would want it so that one function is able to take in the variable names that it is initialised with so that if I had multiple input lines, I would be able to have one function to check all inputs. Alternatively it would probably be preferable for the input line to be outside the function to account for any lines that might want specific text to be displayed rather than generic text.
0 commentaires
Réponse acceptée
David Hill
le 2 Avr 2020
Modifié(e) : David Hill
le 2 Avr 2020
function ans=testNum(z)
str = '';
NaN;
while isnan(ans)
input([str, 'Enter a value for ',z,': ']);
str = 'Please enter a number. ';
end
end
Then just execute the function.
x=testNum('x');
And x will equal whatever number you enter.
2 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Text Data Preparation dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!