Add a vector to a struct array
20 ビュー (過去 30 日間)
古いコメントを表示
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)
0 件のコメント
採用された回答
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 件のコメント
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.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Structures についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!