how to evaluate a string named matrix
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
vincent lin
il 12 Gen 2020
Commentato: vincent lin
il 13 Gen 2020
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 Commento
Adam Danz
il 12 Gen 2020
Modificato: Adam Danz
il 12 Gen 2020
"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.
Risposta accettata
Walter Roberson
il 13 Gen 2020
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});
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrices and Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!