brodoll
brodoll

Reputation: 1881

Convert structure array to matrix

I am trying to convert a structure array to a matrix. Each field of the structure stores a vector that can reach up to 520000 rows. There can be up to 20 fields in a single structure array, but number of rows is the same across the fields.

As a down scaled example consider the structure s, where each field is an integer:

s=struct('a',1,'b',2);
s(2)=struct('a',3,'b',4);
s=s';

In the desired output, each field will correspond to a column. a values will be in the first column, while b values will be in the second:

desiredOutput = [1 2; 3 4];

I have approached this in an indirect way:

cell2mat(struct2cell(s))'

However, this involves two transformations which i find unnecessary due to the well behaved nature of my structure.

I have also approached this using a for loop:

fields = fieldnames(s);
nrows = size(s,1);
ncols = numel(fields);
desiredOutput = nan(nrows,ncols);
for jj=1:ncols
    desiredOutput(:,jj) = [s.(fields{fields(jj)})]';
end

I hoped to find a struct2mat function but it does not exist. Is there a simpler way to accomplish this task that I am not aware of?

Upvotes: 1

Views: 1859

Answers (1)

Debosmit Ray
Debosmit Ray

Reputation: 5413

I had something similar to this written out. So, if you don't mind, I will 'kinda' copy that out over here.

data(1,1).val = 1; 
data(1,2).val = 2; 
data(2,1).val = 3; 
data(2,2).val = 4;

This gives a 2x2 struct with field val.

A = reshape([data.val],size(data))

Now, A looks like this [ 1 2 : 3 4]

A =
      1 2
      3 4

Does that help?

Upvotes: 1

Related Questions