Search code examples
matlabdata-structurescell-array

MATLAB - Access vector from a structure


I have a 1x4 structure called

Fruitbasket=struct('apples',{[1] [2] [3] [4]},'bananas',[],'berries',[],'melons',[])

I'm not sure how to get Fruitbaskets.apples in vector form (e.g., [1 2 3 4]).

All I get for Fruitbaskets.apples is ans=1;ans=2;ans=3;ans=4.


Solution

  • EDIT: It looks like you want to have an array of structures. A very simple solution of catching this values is plainly looping:

    for ii=1:size(Fruitbasket,2)
        app(ii)=Fruitbasket(ii).apples; % or getfield(Fruitbasket(ii),'apples');
    end
    

    That is because you are creating an array of structures, not a structure with arrays!

    Fruitbasket=struct('apples',{[1] [2] [3] [4]},...)
    

    Creates 4 Fruitbaskets, each of them with a single number. You can verify this by doing Fruitbasket(2).apples. If you want the field apples to have an array, do not define it as a cell array bus as a vector. Cell arrays are defined with {} and dovecots with []. The following will create a single struct with a vector in apples:

    Fruitbasket=struct('apples',[1 2 3 4],'bananas',[],'berries',[],'melons',[])