combined operations on struct arrays

I have a struct S
S=struct()
It has 2 fields a,b
S(1).a=2;
S(2).a=3;
S(3).a=4;
now how do i do something like
S(:).a=S(:).a+[ 5 6 7 ]

Answers (1)

S=struct('a',cellfun(@plus, {S.a},{5 6 7},'un',0))

4 Comments

I want something more readable as the example i gave is very simplified.
In reality i have array of struct (having 12 fields) of 100000 elements and i have to do complicated calculation sometimes on S.field1
something on the lines of
S.field1=S.field1 .^ 2+cos(S.field1) +const1* S.field1 .* S.field2
so i am pretty sure this hack will not be useful to me. IS there a better way?
S=struct('field1',cellfun(@(x,y) x^2+cos(x)+const1*x*y, {S.field1},{S.field2},'un',0))
Archit
Archit on 1 May 2013
Edited: Archit on 1 May 2013
as i said, i want something readable which should not be cryptic so ur two answers do not serve me
What do you mean by readable?
doc cellfun

This question is closed.

Tags

Asked:

on 1 May 2013

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!