Adding new field to structure array
Afficher commentaires plus anciens
I have a structure vector s with already existing fields f1 and f2. I want to perform calculations on those fields for every single element and save results to a new field f3. Can following expressions be simplified?
fun = @(x, y) (x+y)/2
a = arrayfun(fun, [s.f1], [s.f2])
a = num2cell(a)
[s.f3] = a{:}
Réponse acceptée
Plus de réponses (1)
Walter Roberson
le 22 Avr 2019
Modifié(e) : Walter Roberson
le 22 Avr 2019
Not really. You could reduce by one line by using
a = num2cell(arrayfun(fun, [s.f1], [s.f2]));
for whatever that is worth.
You could go through struct2cell() and create a new cell with the result, but it is not going to be any simpler than what you already have.
You could do it in fewer lines using especially obscure syntax. I am the only person whom I have seen use that syntax in about a decade -- I posted an example a few months ago just to prove that it could be done -- and that it was not worth doing. It would not be any simpler: it would leave even fairly advanced MATLAB users scratching their heads and wondering, "Can you do that???"
6 commentaires
Alex Mcaulley
le 22 Avr 2019
Another option (I don't know which is more efficient):
fun = @(x, y) (x+y)/2
a = arrayfun(fun, [s.f1], [s.f2],'UniformOutput',false);
[s.f3] = a{:}
Walter Roberson
le 22 Avr 2019
That's a good approach.
madhan ravi
le 22 Avr 2019
Sir Walter is that possible using substruct() and subsasgn() ? It would be nice if it’s possible.
Walter Roberson
le 22 Avr 2019
Yes, using subsasgn() is the very obscure syntax I was referring to.
madhan ravi
le 22 Avr 2019
;) knew it , thank you sir Walter.
Maciej Grybko
le 22 Avr 2019
Catégories
En savoir plus sur Structures dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!