Assigning multiple variables to inputdlg's output string

조회 수: 8 (최근 30일)
Henreee
Henreee 2017년 3월 12일
편집: Stephen23 2017년 3월 13일
Hi,
I need to have the user enter multiple values and then for each value to be assigned as a number to a variable.
The current code I have is:
prompt = {'Enter value 1','Enter value 2','3','4','5','6'};
dlg_title = 'Enter values';
num_lines = 1;
defaultans = {'1','5','5','7','2','11'}
Params = inputdlg(prompt, dlg_title, num_lines, defaultans);
[a,b,c,d,e,f] = str2double(Params{:});
However this gives the error:
Error using str2double
Too many input arguments.
Any help would be great, thanks.

답변 (2개)

Stephen23
Stephen23 2017년 3월 13일
This is easy using a comma-separated list:
prompt = {'Enter value 1','Enter value 2','3','4','5','6'};
defaultans = {'1','5','5','7','2','11'};
Params = inputdlg(prompt, 'MyTitle', 1, defaultans);
C = num2cell(str2double(Params));
[a,b,c,d,e,f] = C{:}
a =
1
b =
5
c =
5
d =
7
e =
2
f =
11
  댓글 수: 2
Jan
Jan 2017년 3월 13일
+1: Perfect. I'm not sure if the indirection over num2cell is faster, but it is much nicer than a subfunction with a loop and varargout.
Stephen23
Stephen23 2017년 3월 13일
편집: Stephen23 2017년 3월 13일
@Jan Simon: I guess the num2cell is going to add a little bit of time, but considering that inputdlg waits many seconds for the user to input a few values, those few milliseconds are unlikely to be noticed.

댓글을 달려면 로그인하십시오.


Jan
Jan 2017년 3월 12일
편집: Jan 2017년 3월 13일
data = str2double(Params);
If you really want to split this to 5 variables:
a = data(1);
b = data(2);
c = data(3);
d = data(4);
e = data(5);
But either use smarter names for the variables or keep them as a vector, if it matchs the underlying problem.
[EDITED] If you really want to split the vector to different variables, you can do this with a small function:
function varargout = SplitToVars(data)
if nargout ~= numel(data)
error('Number of inputs does not match number of outputs.');
end
for iVar = 1:numel(data)
varargout{iVar} = data(iVar);
end
end
  댓글 수: 2
Henreee
Henreee 2017년 3월 12일
Thanks for the reply,
The code I put on here was just an example, the actual has a lot more inputs. Is there a way to assign all of the variables at once? I tried
[a,b,c,d,e,f,g,etc] = data(:);
But it gives the error
Insufficient number of outputs from right hand side of equal sign to satisfy assignment.
Even though there are the same number of variables as numbers in data.
Thanks!
Jan
Jan 2017년 3월 13일
편집: Jan 2017년 3월 13일
@Henreee: Even if the number of variables equals the number of data, this is no valid Matlab syntax. Of course this produces an error. You could write a small function for this. See [EDITED] in my answer.

댓글을 달려면 로그인하십시오.

카테고리

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