How to update struct array fields with mutiple values
91 次查看(过去 30 天)
显示 更早的评论
I am trying to update a field value in a struct array. For example if I have 1*10 struct of A with a field in it called B, I want to replace the following loop with another method:
for iLoop=1:10
A(iLoop).B = iLoop;
end
I tried:
[A.B] = deal(1:10);
And also:
A = setfield(A,num2cell(1:10),'B',num2cell(1:10),(1:10));
But none of them worked (the first method assigns the whole (1:10) vector to each 'B' field in the struct array. The second one crashes). Does anyone know how to make it work?
0 个评论
采纳的回答
Walter Roberson
2012-3-5
编辑:Walter Roberson
2019-9-19
t = num2cell(1:10);
[A.B] = t{:};
See comments for the case where the struct does not already exist.
6 个评论
breathi
2019-9-19
Walter,
please edit your answer and insert the solution you posted in the comments.
It was driving me nuts to find out, that only an existing struct array can be filled with your current solution, just to find out a few angry debug steps later that you posted a comment and that this solution could just create a new struct array by explicitly using length(t) as the left side input.
Thanks.
Walter Roberson
2019-9-19
For the case where the struct does not already exist, there is a different method that can be easier:
A = struct('B', t);
where t is the cell array from above. This also permits you to store to multiple fields, and to leave some fields empty, and to put in non-scalar values.
A = struct('B', num2cell(1:10), 'C', [], 'D', num2cell(rand(2,10),1));
更多回答(3 个)
Andrew Newell
2012-3-5
What timing! It happens that the File Exchange Pick of the Week is the function disperse. If you download disperse and put it on your path, you can use the following command:
[A.B] = disperse(1:10);
3 个评论
Mitja M
2018-7-25
I would highly appreciate the solution to the following problem, which I believe is highly related to the previous, but I somehow don't find the appropriate solution.
I have the following variables:
AA, 1×3 struct array with fields: bb
bb, nx6 double array
cc, nx3 double array
n for all three bb and cc arrays is equal to 100 right now
Now I would like to change the fifth column of all three bb arrays to corresponding column in cc array. It can be correctly done using the following for loop:
for i=1:3
AA(i).bb(:,5)=cc(:,i);
end
Is it possible to achieve this without the for loop.
Thank you
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!