how to evaluate a string named matrix
조회 수: 1 (최근 30일)
이전 댓글 표시
I have a name changing matrix
x = sprintf('a_%s_y(1:2)', '2g');
y = sprintf('b_%s_y(1:2)', '2g');
They generate x='a_2g_y(1:2)' and 'b_2g_y(1:2)'.
First how can I detect a_2g_y(1:2) exist or not to avoid undefined variable error?
Second, how can I plot(a_2g_y(1:2), b_2g_y(1:2)) if the matrix exist
댓글 수: 1
채택된 답변
Walter Roberson
2020년 1월 13일
xvar = sprintf('a_%s_y', '2g');
xcol = 1:2;
yvar = sprintf('b_%s_y', '2g');
ycol = 1:2;
if exist(xvar, 'var') && exist(yvar, 'var')
xval = eval(xvar); yval = eval(yvar);
if numel(xvar) >= max(xcol) & numel(yvar) >= max(ycol)
plot(xval(xcol), yval(ycol));
else
fprintf('variables both exist but not large enough\n')
end
else
fprintf('variables do not both exist\n')
end
This code is not recommended.
Do not even give the user an opportunity to specify a variable that does not exist: create a listbox containing only valid variable names, and use it to index into a cell array of the variable values. Or if the variables are being loaded from a .mat file,
variable_struct = load('appropriate .mat file name');
variable_names = fieldnames(variable_struct);
Now give them a listbox from the variable names, and use the selected variable name with dynamic field names:
variable1_index = get(handles.FirstVariable, 'value');
variable2_index = get(handles.SecondVariable, 'value');
first_variable = variable_struct.(variable_names{variable1_index});
second_variable = variable_struct.(variable_names{variable2_index});
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!