Adding new field to a struct in Matlab

64 Views Asked by At

I have a 800x1 struct S with fields A, B, C, D, E, F and G. I want to add an eighth field H where H is a matrix 800x8191 double. There is a 1x8191 row of H for every element of S.

That is, I want to make the assignment S(i)=H(i,:) for every i.

I tried S.H=H or S.Hcalculated=H, but received the error "Scalar structure required for this assignment."

How can I succeed?

3

There are 3 best solutions below

0
Argyll On

You may try

S=arrayfun(@(s,h)setfield(s,'H',cell2mat(h)),S,num2cell(H,2));

For example,

>> S=struct;
>> S.A='a';
>> S(2).A='b';
>> H=[1,2;3,4];
>> H=num2cell(H,2);
>> S=arrayfun(@(s,h)setfield(s,'H',cell2mat(h)),S,H'); % transpose is needed because the shape of S is 1x2

enter image description here

Note: if you need to perform row-wise operations on H, you should consider doing that first before appending its rows onto S for efficiency reasons.

0
Cris Luengo On

There are two steps:

  1. Separate the matrix H into a separate matrix for each row.
  2. Assign the new matrices H to S.H using deal.

Example:

This is example data, S is your struct (but of size 3x1 with only a field A for simplicity), H is a 3x10 array, where the first dimension matches the length of S:

S = struct('A', {'a', 'b', 'c'})';
H = randn(3, 10);

The two steps described above:

H = num2cell(H, 2);
[S.H] = deal(H{:});
0
Wolfie On

For completeness as it's not mentioned in other answers, you could of course just use a for loop. I don't really see a reason to avoid it:

for i = 1:size(H,1)
   S(i).H = H(i,:); 
end