Setting variable names inside function based on input arguement in MATLAB
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Richard Cheung
am 2 Apr. 2020
Kommentiert: Richard Cheung
am 2 Apr. 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 Kommentare
Akzeptierte Antwort
David Hill
am 2 Apr. 2020
Bearbeitet: David Hill
am 2 Apr. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Text Data Preparation finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!