Home > utils > convert_structarray.m

convert_structarray

PURPOSE ^

SYNOPSIS ^

function s_out = convert_structarray(s_in)

DESCRIPTION ^

 Accepts a struct with fields containing vectors of values, where
 the order of the elements of each vector link the values in the 
 fields to one another. This function converts this type of struct
 to an array of structs, where each instance in the array contains 
 a single value from the vectors contained in the original fields.
 
 i.e. - a struct such as the following:

 myStruct = 
       field1: [100 x 1 double]
       field2: [100 x 1 double]
       field3: {100 x 1 cell}


 is converted to the following:

 myConvertedStruct = 
       1x100 struct array with fields:
             field1
             field2
             field3

 16 Jan, 2007 - First Version, S.T.

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 function s_out = convert_structarray(s_in)
0002 %
0003 % Accepts a struct with fields containing vectors of values, where
0004 % the order of the elements of each vector link the values in the
0005 % fields to one another. This function converts this type of struct
0006 % to an array of structs, where each instance in the array contains
0007 % a single value from the vectors contained in the original fields.
0008 %
0009 % i.e. - a struct such as the following:
0010 %
0011 % myStruct =
0012 %       field1: [100 x 1 double]
0013 %       field2: [100 x 1 double]
0014 %       field3: {100 x 1 cell}
0015 %
0016 %
0017 % is converted to the following:
0018 %
0019 % myConvertedStruct =
0020 %       1x100 struct array with fields:
0021 %             field1
0022 %             field2
0023 %             field3
0024 %
0025 % 16 Jan, 2007 - First Version, S.T.
0026 
0027 
0028 
0029 if(~isstruct(s_in) | (length(s_in) > 1))
0030   error('input argument must be a struct of length 1');
0031 end
0032 
0033 
0034 fldnames = fieldnames(s_in);
0035 
0036 %first check the the vector lengths of all fields are the same
0037 %before proceeding
0038 for ifld = 1:length(fldnames)
0039   numElements(ifld) = length(getfield(s_in,fldnames{ifld}));
0040 end
0041 
0042 if(sum(diff(numElements)) ~= 0)
0043   error(['The lengths of all fields in the struct must be the same' ...
0044      ' to use the function']);
0045 end
0046 
0047 newStruct = mkstruct(fldnames);
0048 
0049 s_out = repmat(newStruct,1,numElements(1));
0050 
0051 
0052 for ifld = 1:length(fldnames)
0053   valVector = getfield(s_in,fldnames{ifld});
0054   for iElement = 1:numElements
0055     if(iscell(valVector(iElement)))
0056       val = valVector{iElement};
0057     else
0058       val = valVector(iElement);
0059     end
0060     s_out(iElement) = setfield(s_out(iElement),fldnames{ifld},val);
0061   end
0062 end

Generated on Wed 20-Sep-2023 04:00:50 by m2html © 2003