How can I assign/save a function output to one field of a struct across multiple elements?
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Geethanjali Pavar
il 27 Ott 2016
Commentato: Geethanjali Pavar
il 8 Nov 2016
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 :)
0 Commenti
Risposta accettata
James Tursa
il 27 Ott 2016
Modificato: James Tursa
il 27 Ott 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{:});
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Structures in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!