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