Adding new field to structure array

조회 수: 8 (최근 30일)
Maciej Grybko
Maciej Grybko 2019년 4월 22일
댓글: Maciej Grybko 2019년 4월 22일
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{:}

채택된 답변

Maciej Grybko
Maciej Grybko 2019년 4월 22일
편집: Maciej Grybko 2019년 4월 22일
Okay, I figured it out:
fun = @(x, y) (x+y)/2
a = arrayfun(fun, [s.f1], [s.f2], 'UniformOutput',false)
[s.f3] = a{:}
But still, is there any way to combine 2nd and 3rd line?
  댓글 수: 1
madhan ravi
madhan ravi 2019년 4월 22일
Isn’t that what Alex posted 30 minutes earlier to this?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2019년 4월 22일
편집: Walter Roberson 2019년 4월 22일
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
madhan ravi
madhan ravi 2019년 4월 22일
;) knew it , thank you sir Walter.
Maciej Grybko
Maciej Grybko 2019년 4월 22일
Thanks

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by