Monday, June 15, 2015

Convert struct of single-value fields into a 2D matrix

Suppose that we have a dataset of N records, each records is a struct of M fields, and each field has just a single numeric value. Now, we want to convert this struct-type dataset into a matrix for further manipulation. What should we do? The following figure will tell you the way:

 Following is the brief description for functions used:
  • struct2cell(): converts the m-by-n structure s (with p fields) into a p-by-m-by-n cell array c.
  • B=squeeze(A): returns an array B with the same elements as A, but with all singleton dimensions removed.
And here is the sample MATLAB code:
Xstruct = importdata([getCurrentFolder() '\..\data\somename.mat']);
Xcell=struct2cell(Xstruct);
X=squeeze(Xcell)';
X=cell2mat(X);
Thank for reading!
(Nguyen My - 2015/06/16)

0 comments:

Post a Comment