Iterating through Struct MATLAB

287 views Asked by At

Below is what I have so far. I need to iterate through each field of rxnsBothKaletaS struct where each field represents a nx4 cell. I need to extract information out of the first column of that cell as a single string separated by commas and then assign it to an index of the field in fname.

(To give the context: fname are names of the genes and within eaach gene are reactions that rely on that gene. I need to extract all of the reactions for a given gene and have them all as a string separated by commas)

fname = fieldnames(rxnsBothKaletaS)
for  i = 1:numel(fname)
    gene = rxnsBothKaletaS.(fname{i})

    for j = 1:size(gene,1)
        rxns = rxns + char(string(gene(j,1)));
    end 

    fname(i,2) = rxns; 
end
1

There are 1 answers

2
Suever On

You can use structfun to iterate through the fields of a struct. Then within the anonymous function that we will apply to each field, we can use strjoin to join all strings in the first column of x together with commas.

fnames = structfun(@(x)strjoin(x(:,1), ','), rxnsBothKaletaS, 'UniformOutput', 0);