1-line equivalent of try / catch in MATLAB

I have a situation in MATLAB where I want to try to assign a struct field to a new variable, for example:

swimming = fish.carp;

BUT the field carpmay or may not be defined. Is there a way to specify a default value if carpit is not a valid field? For example, in Perl I would write

my $swimming = $fish{carp} or my $swimming = 0; 

where 0 is the default value, and orindicates the action that should be performed if the assignment fails. It seems like something similar should exist in MATLAB, but I cannot find any documentation on it. For ease of reading the code, I would prefer not to use a statement ifor block try/catchif I can help him.

+4
source share
3 answers

You can make your own function to handle this and keep the code pretty clear. Sort of:

swimming = get_struct(fish, 'carp', 0);

with

function v = get_struct(s, f, d)

if isfield(s, f)
    v = s.(f);   % Struct value
else
    v = d;       % Default value
end

Best

+4
source

From what I know, you cannot do this on one line in MATLAB. MATLAB logical constructs require explicit operators if/elseand cannot do this on the same line ... as in Perl or Python.

What you can do is check if the structure contains a fishfield carp. If it is not, you can set the default value to 0.

Use isfieldto help you with this. Therefore:

if isfield(fish, 'carp')
    swimming = fish.carp;
else
    swimming = 0;
end

Also, as Ratbert said, you can put it on one line with commas ... but again, you still need a construct if/else:

if isfield(fish,'carp'), swimming = fish.carp; else, swimming = 0;

, , 0.

function [out] = get_field(S, field)
    if isfield(S, field)
        out = S.(field);
    else
        out = 0;
    end

:

swimming = get_field(fish, 'carp');

swimming 0, fish.carp. , , , , .

+3

, , , , script.

helper = {@(s,f) 0, @(s,f) s.(f)}
getfieldOrDefault = @(s,f) helper{ isfield(s,f) + 1 }(s,f)

fish.carp = 42

a = getfieldOrDefault(fish,'carp')
b = getfieldOrDefault(fish,'codfish')

a =  42

b =  0
+3

All Articles