How to update struct array fields with mutiple values
Mostrar comentarios más antiguos
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?
Respuesta aceptada
Más respuestas (3)
Andrew Newell
el 5 de Mzo. de 2012
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 comentarios
Mohammad Tabesh
el 5 de Mzo. de 2012
Bradley Stiritz
el 15 de Sept. de 2018
Thank you Andrew! disperse() is just what I needed.
This works perfectly, until you have a field in between.
[A.B] = t{:}; %Great!
[A.B(1).C] = t{:}; % doesn't work
Anyone have a suggestion on how to make it work this way?
1 comentario
Mohammad Tabesh
el 13 de Feb. de 2018
Mitja M
el 25 de Jul. de 2018
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
1 comentario
Mohammad Tabesh
el 26 de Jul. de 2018
Categorías
Más información sobre Cell Arrays en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!