inputdlg saves input as a cell and not an array
조회 수: 8 (최근 30일)
이전 댓글 표시
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
답변 (1개)
BhaTTa
2024년 6월 11일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!