Using the exist function, on a user defined variable in a function.
Mostrar comentarios más antiguos
So I am creating a function with a user input. In order to get full credit we have to check first to see if the input exists. The issue is that to use the exist function the variable name has to be made into a string exist('variable','var'), but the variable is an input. So my question is, how I do use the exist function in this scenario.
function M=get_mass_matrix(vibration_model, FSAE_Race_Car)
if 1 == exist('FSAE_Race_Car', 'var')
M=FSAE_Race_Car.mass
else
M='error, input does not exist'
end
end
Example script:
X=get_mass_matrix('1_DOF', car_2010)
where car_2010 is a predefined structure and exists and should run and give a value but
X=get_mass_matrix('1_DOF', car_2009)
where car_2009 is not a predefined structure and does not exist and should give an error message.
Respuesta aceptada
Más respuestas (1)
dpb
el 29 de Sept. de 2016
Use inputname to find the name of the variable passed to the function and check its existence. But, of course, it has to have existed or the call will have failed when it attempts to run so the test inside the function is useless.
Example from the workspace here--
>> whos
Name Size Bytes Class Attributes
STRS 1x2 154 cell
ans 2x2 294 cell
data 2x1 16 double
ds 2x2 1290 dataset
filecontent 1x264 528 char
fmt 1x13 26 char
fmts 1x2 128 cell
i 1x1 8 double
keys 9x1 694 cell
keyvaluepairs 13x2 1848 cell
rows 13x1 104 double
s 17x1 1480 cell
txt 2x1 138 cell
values 9x1 2388 cell
x 2x2 32 double
y 2x2 32 double
>> mean(z)
Undefined function or variable 'z'.
>>
There is no z so if try to call a function with it; no can do. So, mean in this case checking on the existence of z is futile; it'll never get there to do so.
3 comentarios
Joshua Barton
el 29 de Sept. de 2016
dpb
el 29 de Sept. de 2016
The point is that the function can't ever get called if the argument(s) don't exist. That particular error can never happen.
Joshua Barton
el 29 de Sept. de 2016
Categorías
Más información sobre Variables en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!