how insert array in field struct
Mostrar comentarios más antiguos
Z is matrix number
for i=1:width(A)
A(i).b=z(:,i)
end
it's possibile to avoid loop?
Respuesta aceptada
Más respuestas (2)
"it's possibile to avoid loop?"
Does A already exist or not? Your question does not make this clear... here are both cases:
Z = [1,2,3; 4,5,6; 7,8,9]
C = num2cell(Z,1);
A = struct('a',C) % structure does not exist
[A.b] = C{:} % structure already exists
Checking:
A.b
Read more:
Rahul
el 13 de Jul. de 2023
Hi Luca,
This is possible. You can try out the following code for same.
A = struct('b', cell(1, width(A))); % Preallocate struct array
% Assign columns of z to the field 'b' of each struct element in A
[A.b] = deal(z);
Here deal(z) is used to assign each column of z to the corresponding field b in each struct element of A. This way, you can avoid the need for a loop and achieve the desired assignment efficiently.
Make sure that the number of columns in z matches the number of elements in A (i.e., width(A) or numel(A)).
Hope this helps.
Thanks.
3 comentarios
Image Analyst
el 13 de Jul. de 2023
It's not clear if you want
- an array of structures (82 A's) with each structure having one field "b" which is a column vector of 82 elements, OR
- if you want a single structure (one A, not an array of 82 of them) and that one structure has a single field which is an 82 element column vector.
Your initial code seems to indicate 1 -- an array of structures, but is that really true?
Why do you want to avoid the loop anyway? With a microscopic data size like 82, a for loop may well be faster than messing around with inefficient cell arrays. Either way will be so fast you won't be able to perceive a difference between them anyway.
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
