Home > Back-end >  Rearange matlab struct
Rearange matlab struct

Time:02-19

Lets have a struct defined like this:

s.a = [1, 11]; 
s.b = [2, 22];

How can I convert it to struct defined like this:

s(1).a = 1;
s(1).b = 2;
s(2).a = 11;
s(2).b = 22;

This need comes from textscan() function. I read large file using this function and then convert the result using cell2struct() function. In this case, however, each field contains whole column, so one has to address individual value by s.column_name(row_index). While I would prefer to do it by s(row_index).column_name.

CodePudding user response:

This type of operation with a struct array does not usually result in pretty code, but here it goes:

s2 = cell2struct(num2cell(cell2mat(struct2cell(s))).', fieldnames(s), 2);

In general, indexing a struct array across its two "dimensions" (fields and array index) is problematic for this reason. Have you considered using a table instead? It allows both types of indexing in a natural way:

s = table; % initiallize as table
s.a = [1; 11]; % note: column vectors
s.b = [2; 22];

So now

>> s
s =
  2×2 table
    a     b 
    __    __
     1     2
    11    22
>> s.a
ans =
     1
    11
>> s.a(2)
ans =
    11
>> s(:, 'a') % note: gives a (sub)table
ans =
  2×1 table
    a 
    __
     1
    11
>> s{:, 'a'} % same as s.a
ans =
     1
    11
>> s{2, :}
ans =
    11    22
>> s{2, 'a'} % same as s.a(2)
ans =
    11

CodePudding user response:

A possible simple solution would be the following:

fn = fieldnames(s);
for j = 1 : numel(fn)
    for k = 1 : numel(s(1).(fn{j}))
        s2(k).(fn{j}) = s.(fn{j})(k);
    end
end
  • Related