Ask an expert. Trust the answer.

Your academic and career questions answered by verified experts

How to exist(obj.struct.var)?

Date: 2023-07-29 14:44:10

exist(obj.struct.var) always returns 0 regardless if the var exists or not.

Answer:

If you're not sure if the obj variable is a struct or has a field named struct, you can call isfield twice.

 

y = isfield(obj, 'struct') && isfield(obj.struct, 'var');

The first isfield call will return false if obj is not a struct or is a struct that does not have a field named struct. Only if the first isfield call returns true will the short-circuit && operator cause the second isfield call to be evaluated. In fact, that documentation page includes an example (Change Structure Field Value) that is somewhat related to this question.

 

obj = 42; % Not a struct
y1 = isfield(obj, 'struct') && isfield(obj.struct, 'var') % false

obj = struct('abc', 'def'); % struct but without the correct field
y2 = isfield(obj, 'struct') && isfield(obj.struct, 'var') % false

obj = struct('struct', struct('var', 'std'));
y3 = isfield(obj, 'struct') && isfield(obj.struct, 'var') % true

 


Why Matlabhelpers ?

Our Matlab assignment helpers for online MATLAB assignment help service take utmost care of your assignments by keeping the codes simple yet of high-quality. We offer the most reliable MATLAB solutions to students pursuing their Computer Science course from the Monash University, the University of Sydney, the University of New South Wales, the University of Melbourne; to name a few. Approach us today for best Matlab solutions online!

whatsApp order on matlabhelpers.com

telegram order on matlabsolutions.com