Asking for user input only once with input, or take values like pi/3 with inputdlg

1 次查看(过去 30 天)
I have a function that calculates when you input values for n, for x, for y. Now I need to ask the user for input. I prefer how inputdlg asks for input so I wrote the following (where seriessum is my function, written in another .m file):
a=inputdlg({'Enter a value for n', 'Enter a value for x', 'Enter a value for y'}, 'ΣS=(x/y).^i, for i=1:n')
a1=zeros(1,3);
for k=1:3
a1(k)= str2double(cell2mat(a(k))); %takes the cell array and converts it into a regular array and then the string into an integer
end
seriessum(a1(1),a1(2),a1(3))
This works for most inputs, however, I realised it doesn't work for inputs like 'pi/4' or similar.
That's when I decided that I would use a regulat input function and wrote:
promptn = 'Enter an integer value for n';
promptx = 'enter a value for x';
prompty= 'Enter a value for y';
n = input(promptn)
x = input(promptx)
y = input(prompty)
seriessum(n, x, y)
But in this case, the prompts keep appearing in the workspace (I mean: I enter a value for n, for x and for y, and I'm immediately asked to enter a value for n again).
I would like to know if I can fix any of this issues. The second issue is more of an inconvenience because it does calculate the sum anyways.

采纳的回答

ME
ME 2019-12-20
When you use the inputdlg function and input something like pi/4 it appears to save everything as a cell array of strings. You can always use str2num() to convert the string back into a numerical form - see the below example copied directly from my command window.
a =
3×1 cell array
{'pi/4'}
{'pi/3'}
{'pi' }
>> a{1}
ans =
'pi/4'
>> str2num(a{1})
ans =
0.7854

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by