Kevin
Kevin

Reputation: 229

check with Matlab if object is exsting

Matlab code:

for n = 1:length(data)

    if exist('data{n}.sid')
        array{n} = data{n}.sid
    else
        array{n} = 0
    end

end

Result:

array = 

    [0]    [0]    [0]    [0]    [0]    [0]    [0]

But in the first and the second struct of "data", the "hk1", resp. the "hk1.sid" exists and contains "1"!

How do I have to change my code, that the array looks like this?...

array = 

    [1]    [1]    [0]    [0]    [0]    [0]    [0]

Content of data:

>> data

data = 

    [1x1 struct]    [1x1 struct]    [1x1 struct]    [1x1 struct]    [1x1 struct]    [1x1 struct]    [1x1 struct]

>> data{2}

ans = 

    sid: 1
    hk1: [1x1 struct]

>> data{4}

ans = 

          pack_id: [1x1 struct]
    pack_seq_ctrl: [1x1 struct]

As you see, data{2} includes "sid", but data{4} doesn't include "sid"...

Upvotes: 0

Views: 116

Answers (2)

Divakar
Divakar

Reputation: 221574

See if this isfield + cellfun based approach works for you -

fn1 = 'hk1' %// stage1 search fieldname
fn2 = 'sid' %// stage2 search fieldname

%// logical array, where 1s mean first stage fieldname 'hk1' exists in data struct
stage1_matches = cellfun(@(x) isfield(x, fn1),data) 

%// get the actual indices as we will need these later on 
stage1_idx = find(stage1_matches) 

%// logical array, where 1s indicate second stage fieldname 'sid' exists in 
%// data.hk1 struct
stage2_matches = cellfun(@(x) isfield(x.hk1,fn2),data(stage1_matches))  

 %// find the indices from stage1_idx where 'sid' fieldname is not  present 
 %// and index into the logical array of stage1_matches to set those as zeros 
 %// and thus we have the desired output
stage1_matches(stage1_idx(~stage2_matches)) = 0 

Upvotes: 0

Sam Roberts
Sam Roberts

Reputation: 24127

Instead of exist('data{n}.sid'), use isstruct(data{n}) && isfield(data{n}, 'sid').

exist is attempting to check whether a variable exists that is literally called data{n}.sid. That's not a valid variable name, so it always returns false and you never get through to the condition you wanted.

Upvotes: 2

Related Questions