필터 지우기
필터 지우기

Add a vector to a struct array

조회 수: 20 (최근 30일)
Frank
Frank 2014년 8월 21일
편집: Sean de Wolski 2014년 8월 22일
I have a struct array, say
a(1).b=1
a(2).b=1
a(1).c=1
a(2).c=1
and an vector, say
c=[1 2]
Now I want to add vector c to a, in order to obtain something like a.c
How can I do this without a for-loop? (actually the length of the struct is not 2, but thousands)

채택된 답변

Sean de Wolski
Sean de Wolski 2014년 8월 21일
편집: Sean de Wolski 2014년 8월 21일
You could use a for-loop (which would be the easiest to understand) and may be the fastest. Or you could use comma-separated list expansion which is trickier.
a(1).b=1
a(2).b=1
a(1).c=1
a(2).c=1
c = [pi exp(1)];
c = num2cell(c)
[a(:).c] = c{:}
a.c
Frankly, I would recommend avoiding this structure altogether. Why not have a 1x1 struct with a field c which is a 1xn?
a.c = [1 2]
a.c(2)
  댓글 수: 2
Frank
Frank 2014년 8월 21일
Thank you.
As for avoiding this structure: I recognized in the meantime, that there is more overhead when using the struct arrays. But the struct arrays are part of a major legacy Matlab program, and I have to live with it for the moment.
As far as I know it is good Matlab practise to avoid for-loops due to low speed, so I hoped there is a single command to shuffle vector data into struct arrays. But now it appears that it might not be possible.
Sean de Wolski
Sean de Wolski 2014년 8월 22일
편집: Sean de Wolski 2014년 8월 22일
That's exactly what my first approach does! It uses comma separated list expansion (instead of a for-loop) on both the left and right hand side to distribute the elements.
Of course MATLAB is plenty fast with loops and has been for a while.

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

추가 답변 (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