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 个评论
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