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

5 次查看(过去 30 天)
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 :)

采纳的回答

James Tursa
James Tursa 2016-10-27
编辑:James Tursa 2016-10-27
[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 个评论
Geethanjali Pavar
Geethanjali Pavar 2016-11-8
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.)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by