Effacer les filtres
Effacer les filtres

Check if variable exists in workspace to plot variable, else generate error

2 103 vues (au cours des 30 derniers jours)
Hi there,
I am having some trouble with checking if a variable exists in the workspace. If the variable exists (which is a structure with time), it should plot the data in my GUI. If the variable does not exist, it should generate an error.
I used this code, however it will always generate an error even if the variable does exist in the workspace. I cannot find what I am doing wrong.
function AmechM_Callback(hObject, eventdata, handles)% Executes on button press in AmechM.
if exist('AmechM','var')
AmechM = evalin('base','AmechM');
plot(AmechM.time,AmechM.signals.values);
xlabel(handles.ax1,'time (s)');
ylabel(handles.ax1,'Acceleration (rad/s²)');
else
errordlg('The workspace does not contain any data. Run a simulation first.','Error');
end
  2 commentaires
per isakson
per isakson le 9 Jan 2015
"exists in the workspace" &nbsp which workspace, that of the callback function or the base?
Maarten
Maarten le 9 Jan 2015
The base workspace.

Connectez-vous pour commenter.

Réponse acceptée

per isakson
per isakson le 9 Jan 2015
Modifié(e) : per isakson le 9 Jan 2015
replace
if exist('AmechM','var')
by
if exist('AmechM','var') == 1
or rather by
ise = evalin( 'base', 'exist(''AmechM'',''var'') == 1' )
if ise
since you want to know whether AmechM exists in the base workspace
and read the on-line help on exist and on "scope"
  8 commentaires
Moritz Plinke
Moritz Plinke le 14 Fév 2020
Modifié(e) : Moritz Plinke le 14 Fév 2020
I know answer is really late but I struggled on a very similar case. My solution is using the function fieldnames().
contains( fieldnames( variable_to_inspect) , 'sub_variable_name_string' )
To make it suitable and robust for "if", use sum()
sum( contains( fieldnames( variable_to_inspect ) , 'sub_variable_name_string' ) )
Alex Morgan
Alex Morgan le 16 Août 2022
Yes, I think fieldnames is the best solution for structures

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by