MATLAB: Copy the values of multiple fields in a structure to another structure at once

structures

Hello,
I want to copy the values of multiple fields in a structure to another structure at once (without loop). For example, suppose the following empty structure.
A.SM = []; p = repmat(A, 3, 1); % 3 is not fixed
Now, I want to copy the contents of another structure which is as follows:
X(1).SM(:)
ans =
4 0 5 0
1 0 1 0
ans =
5 3 0 4
1 1 0 2
ans =
5 4 0 3
2 1 0 1
"p.SM = X(1).SM" does not work.
Many thanks for your help!

Best Answer

To do it without a loop, you would have a small number of choices:
  1. arrayfun() subsasgn . This can be used even when not all of p is being written to. It is rather obscure and not recommended. In nearly any case you would consider using subsasgn this way, any time efficiency you might gain would be outweighed by the cost of figuring out how to write the code, and debugging the code, and documenting it thoroughly. And arrayfun() is, except for some obscure cases that only Jan seems to ever use, slower than a loop
  2. In the case where all of p is being replaced, p = struct('SM', {X(1).SM}); This kind of approach can be useful and efficient in the situations in which it applies.
  3. struct2cell(p) and struct2cell(X(1).SM) and replace parts of the p converted cell with that, and then cell2struct() the result. This has a fair overhead.
  4. You might be able to rig something with setfield()
Typically the most efficient code for this kind of purpose is a loop, which also has the advantage of being really easy to read and debug.
Note: X(1).SM cannot possibly have the output you show. You would need to have one more layer of field name, or else X would have to be a non-scalar array, in which case you would be looking at X(:).SM