inputdlg saves input as a cell and not an array
5 views (last 30 days)
Show older comments
Hello everyone.
I have a problem with 'inputdlg'.
I want to enter a (for example) 2*3 numerical array, when the input dialog box appears(for example my input will be [1 2 3;4 5 6]).
The problem is, this input is saved as a 1*1 cell and there is no way I can convert it to an ordinary array with numerical values.
I have already tried 'cell2mat' and 'str2double' (but maybe not using them in the right way).
By the way I am using Matlab 2016a.
Thanks for any suggestions.
0 Comments
Answers (1)
BhaTTa
on 11 Jun 2024
When you use inputdlg in MATLAB, the input you get is indeed a cell array of strings. If you enter a matrix in the format [1 2 3; 4 5 6], MATLAB treats this as a single string. To convert this string back into a numerical matrix, you need to parse the string correctly.
Here's how you can achieve what you're looking for:
% Prompt the user for input
prompt = {'Enter a matrix:'};
dlgtitle = 'Input';
dims = [1 35];
definput = {'[1 2 3; 4 5 6]'};
answer = inputdlg(prompt, dlgtitle, dims, definput);
% Check if an answer was provided
if ~isempty(answer)
% Convert the answer from cell to string
answerStr = answer{1};
% Safely evaluate the input string to convert it to a numerical matrix
try
% Attempt to evaluate the input string
matrix = eval(answerStr);
% Check if the result is a numeric matrix
if isnumeric(matrix)
disp('The matrix is:');
disp(matrix);
else
error('Input is not a numeric matrix.');
end
catch ME
% Handle cases where the input cannot be evaluated to a matrix
disp(['Error converting input to a matrix: ', ME.message]);
end
end
0 Comments
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!