1

Given two struct arrays A and B with field f1:

A = struct('f1',{1,2,3})
B = struct('f1', {4,5,6})

you can assign the contents of the f1 fields of struct array A to the fields of B by

[B.f1] = A.f1

but I cannot figure out what to do if you want to perform arithmetics on the field, for instance if you want to store the negative of the f1 fields of A in B.

[B.f1] = -A.f1

does not work, you need to first concatenate the elements of A in order for the operator to work

-[A.f1]

but then the result is a vector, which somehow you need to "unwrap" in order to match the number of output arguments.

1 Answer 1

3

You can use num2cell:

tmp=num2cell(-[A.f1]);
[B.f1]=tmp{:};

Result:

B.f1

ans =
    -1
ans =
    -2
ans =
    -3
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I tried using deal but without num2cell and it appears that it's actually num2cell that does all the heavy lifting. It's not even necessary to use deal, [B.f1]=tmp{:}; works just as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.