Karim
Karim

Reputation: 302

How to pass an argument to 'isa' function in matlab

I want to check a variable is existing in Matlab workspace, then check its class. All thing was done by commands in m file. In the case, the name of the variable is a symbolic or character, how I can use isa function.

a='x';
isa(a,'timeseries')

the above code is not worked, but if I change to

isa(x,'timeseries')

it is ok, so how I can check the class of an object by not directly pass its name? Thank you!

Upvotes: 0

Views: 269

Answers (2)

Suever
Suever

Reputation: 65460

You cannot use isa like that because when you pass a string as the first argument to isa, the class of that string is a char

isa('x', 'double')
%   0

isa('x', 'char')
%   1

You could use eval to pass the value of x to isa

isa(eval('x'), 'double')

However the better approach is to explicitly get the class of the variable using whos

S = whos('x');
strcmp(S.class, 'double')
%   1

Upvotes: 0

Cris Luengo
Cris Luengo

Reputation: 60635

You want to use the function exist: https://www.mathworks.com/help/matlab/ref/exist.html

if exist('x','var')
   class(x)
end

You pass a string with the name of the variable to exist. Once you have established it exists, you can use it in your isa call.

Upvotes: 1

Related Questions