How can I assign/save a function output to one field of a struct across multiple elements?

5 views (last 30 days)
I have a function that operates on each element of a struct, combining three of the fields and assigning the output to another (previously initialised) field in the dataset. I am using a for loop to apply the function to each element of the struct but I would rather apply it to the whole struct, omitting the for loop completely.
I have written a line of code accordingly:
[myStruct(:).outputField] = sqrt([myStruct(:).inputField1].^2 + [myStruct(:).inputField2].^2 + [myStruct(:).inputField3].^2);
But I get the error "Error using sqrt. Too many output arguments."
I can assign the RHS to a variable (e.g. test) but when I try to assign test to the LHS, I get the error "Insufficient number of outputs from right hand side of equal sign to satisfy assignment."
Interestingly,
[myStruct(:).outputField] = [myStruct(:).outputField];
gives the same error, despite the two sides being obviously identical.
I suspect that some form of element-wise assignment is what's needed but I haven't been able to work out the correct syntax.
I found a near-identical question here: Applying functions and assignments on multiple struct fields with only one command but I don't understand how the solution works nor why the conversion to/from a cell is necessary. I am therefore hesitant to incorporate the method into my code.
I have programmed before but I am new to MatLab so I would really appreciate if those that are kind enough to answer could use as much plain English as possible :)

Accepted Answer

James Tursa
James Tursa on 27 Oct 2016
Edited: James Tursa on 27 Oct 2016
[myStruct.outputField] = deal(whatever);
Using the brackets on the lhs creates the multiple output requests. The deal on the rhs detects the number of outputs requested and assigns the results accordingly.
doc deal
E.g., using something close to what you have tried as a simple test case, this would have worked:
[myStruct(:).outputField] = deal([myStruct(:).outputField]);
To get your desired calculations done, you could write a loop of course. Or you can use the following (which simply hides the loops in the background):
fun = @(x,y,z) sqrt(x.^2 + y.^2 + z.^2);
s = cellfun(fun,{myStruct.inputField1},{myStruct.inputField2},{myStruct.inputField3},'uni',false);
[myStruct.outputField] = deal(s{:});
  1 Comment
Geethanjali Pavar
Geethanjali Pavar on 8 Nov 2016
Thank you! That is exactly what I needed to know and works perfectly.
(P.S. Sorry for the delay, I had to put this project aside for a while and didn't get a chance to try your solution until today.)

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!