convert field of a struct into an array in matlab

You can use the struct2array function in MATLAB to convert a field of a structure into an array. Here's an example:

main.m
% define a sample structure with a field
myStruct.field1 = [1 2 3];
myStruct.field2 = [4 5];

% convert the contents of field1 into an array
arrayFromField1 = struct2array(myStruct.field1);
190 chars
7 lines

The struct2array function returns the contents of the specified field in the form of an array. In this example, the contents of myStruct.field1 (i.e., [1 2 3]) are returned as an array stored in the arrayFromField1 variable.

Note that if the specified field contains more than one element (e.g., a matrix), struct2array will return a column vector of the concatenated elements. If you want to maintain the original dimensions of the field contents, you can use the num2cell function to convert the field contents to a cell array, and then use cell2mat to convert the cell array to an array:

main.m
% define a sample structure with a matrix field
myStruct.field1 = [1 2; 3 4];
myStruct.field2 = [4 5];

% convert the matrix in field1 into an array with original dimensions
cellFromField1 = num2cell(myStruct.field1, 1);
arrayFromField1 = cell2mat(cellFromField1);
265 chars
8 lines

In this example, num2cell is used to convert myStruct.field1 into a cell array with each matrix row as a separate cell, and cell2mat is used to convert the cell array back into the original matrix format.

gistlibby LogSnag