how to evaluate a string named matrix

조회 수: 1 (최근 30일)
vincent lin
vincent lin 2020년 1월 12일
댓글: vincent lin 2020년 1월 13일
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
Adam Danz
Adam Danz 2020년 1월 12일
편집: Adam Danz 2020년 1월 12일
"First how can I detect a_2g_y(1:2) exist or not to avoid undefined variable error"
It sounds like you might be creating dynamic variable names which causes more problems than it solves.
If so, instead, store your values in a cell array or structure.

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

채택된 답변

Walter Roberson
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 CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by