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!