Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some efficient ways to combine two structures in MATLAB?

Tags:

I want to combine two structures with differing fields names.

For example, starting with:

A.field1 = 1; A.field2 = 'a';  B.field3 = 2; B.field4 = 'b'; 

I would like to have:

C.field1 = 1; C.field2 = 'a'; C.field3 = 2; C.field4 = 'b'; 

Is there a more efficient way than using "fieldnames" and a for loop?

EDIT: Let's assume that in the case of field name conflicts we give preference to A.

like image 247
KennyMorton Avatar asked Sep 02 '08 00:09

KennyMorton


People also ask

How do you merge two structures in Matlab?

To concatenate structures, they must have the same set of fields, but the fields do not need to contain the same sizes or types of data. Just as concatenating two scalar values such as [1,2] creates a 1-by-2 numeric array, concatenating struct1 and struct2 creates a 1-by-2 structure array.

How do I combine two arrays in Matlab?

You can use the square bracket operator [] to concatenate. For example, [A,B] or [A B] concatenates arrays A and B horizontally, and [A; B] concatenates them vertically.

How do you convert a struct to an array in Matlab?

C = struct2cell( S ) converts a structure into a cell array. The cell array C contains values copied from the fields of S . The struct2cell function does not return field names. To return the field names in a cell array, use the fieldnames function.

How do you append in Matlab?

str = append( str1,...,strN ) combines the text from str1,...,strN . Each input argument can be a string array, a character vector, or a cell array of character vectors. If any input is a string array, then the output is a string array.


1 Answers

Without collisions, you can do

M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)']; C=struct(M{:}); 

And this is reasonably efficient. However, struct errors on duplicate fieldnames, and pre-checking for them using unique kills performance to the point that a loop is better. But here's what it would look like:

M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];  [tmp, rows] = unique(M(1,:), 'last'); M=M(:, rows);  C=struct(M{:}); 

You might be able to make a hybrid solution by assuming no conflicts and using a try/catch around the call to struct to gracefully degrade to the conflict handling case.

like image 127
SCFrench Avatar answered Oct 18 '22 01:10

SCFrench