Assign value to the same field of every element of non-scalar struct

风流意气都作罢 提交于 2019-12-21 04:27:35

问题


In Matlab, assigning cell arrays to a struct arrays field foo is possible with

my_array(1000).foo = [];
[my_array.foo] = some_cell{:};

Now what I would like to do is assign a single value to all fields in the array. But whatever I tried, Matlab would return error messages instead of silently assuming that if I want to assign a single element of size [1x1], it should be assigned to all fields. I would be happy if I could simply say e.g.:

my_array.foo = pi;
??? Incorrect number of right hand side elements in dot name assignment.
Missing [] around left hand side is a likely cause.

So, how can I assign a single value to a field all over a struct array?


回答1:


You can use deal to solve this problem:

my_array(1000).foo = [];
[my_array.foo] =deal(pi);

However, note the square brackets in the second line with are necessary to temporarily convert the comma separated list my_array.foo into a vector.



来源:https://stackoverflow.com/questions/12795761/assign-value-to-the-same-field-of-every-element-of-non-scalar-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!