简体   繁体   中英

Referencing Structs inside a Cell Array in Matlab

I'm dealing with a Matlab data structure which is analagous to "MyCellArray" in the following example:

% Create a Struct of string values inside a Cell Array
myCellArray = cell(3,1)
myStruct1 = struct('valA','aaa111','valB','bbb111','valC','ccc111')
myStruct2 = struct('valA','aaa222','valB','bbb222','valC','ccc222')
myStruct3 = struct('valA','aaa333','valB','bbb333','valC','ccc333')
myCellArray{1} = myStruct1
myCellArray{2} = myStruct2
myCellArray{3} = myStruct3

I'd like to be able to efficiently extract some of the data into a new array:

% Extract all valA values from myCellArray    
% ArrayOfValA = myCellArray(< somehow get all the valA values >)
DesiredResult = cellstr(['aaa111';'aaa222';'aaa333']) % Or something similar

I'm new to Matlab and I just can't get my head around the notation. I've tried things like:

ArrayOfValA = myCellArray{(:,1).valA} % This is incorrect notation!

The real data is over 500K lines long so I'd like to avoid for loops or other iterative functions if possible. Unfortunately I can't change the original data structure but I suppose I could take a copy and manipulate that (I tried using struct2cell but I just got into another mess!). Is it possible to do this in a fast and efficient way? Many thanks.

The following appears to work in Octave. I assume it also works in MATLAB:

>> temp = {[myCellArray{:}].valA}
temp =
{
  [1,1] = aaa111
  [1,2] = aaa222
  [1,3] = aaa333
}

Does

myCellAsMat = cell2mat(myCellArray);
ArrayOfValA = vertcat(myCellAsMat(:).valA); 

work?

edit: or horzcat, depending on the dimension and desired output of your valA field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM