From a structure with "n" fields which each are a vector, I want to make a vector of length "n" made of the 3rd value of each vector of my structure.
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Ezio Antonio Mosciatti Urzua
el 3 de Mayo de 2023
This is a situation I have come upon a few times now since I started using structures little time ago.
Specifically in the last case, I have a structure called "file" with 25 fields. On each field I have a vector called "dist" which is a simple 4 value vector. The thing is that I would like a vector with the 3rd value of each of these vectors, somthing like:
a = file(:).dist(4);
Which does not work at all.
I've discovered that if I write:
a = [file(:).dist];
I get a 1x100 vector with all the .dist vectors concatenated. Also, doing:
a=vertcat(file(:).dist);
makes "a" into a 25x4 matrix in which each row is a .dist vector. However, I cannot index directly into that expression as:
a=vertcat(file(:).dist)(:,3);
I realise that I could get this with a little bit of code such as:
for i=1:length(file)
a(i)=file(i).dist(3);
end
and even faster, with the vertcat function as:
a=vertcat(file(:).dist);
a=a(:,3);
But none of these solutions allow me to plot this directly, which is my ultimate goal, in this case.
Thank you!
2 comentarios
Rik
el 3 de Mayo de 2023
Movida: Rik
el 3 de Mayo de 2023
The last solution you mention would be my suggestion, except you don't need the (:).
file = struct('dist',{[1 2 3];[4 5 6]});
a = vertcat(file.dist)
You will need intermediate values anyway, so there is no gain or loss in doing what you already show.
Stephen23
el 3 de Mayo de 2023
Editada: Stephen23
el 3 de Mayo de 2023
Your description "I have a structure called "file" with 25 fields" contradicts the code you show, which indicates that you actually have a structure array with 25 elements and only one field:
for i=1:length(file)
a(i)=file(i).dist(3);
end
DIST is 1 field, not 25 fields. And the indexing FILE(i) indicates that FILE has multiple elements.
% "On each field I have a vector called "dist" which is a simple 4 value vector."
% ^^^^^ element ^^^^^^ field ^^^^^ element
Respuesta aceptada
Stephen23
el 3 de Mayo de 2023
Editada: Stephen23
el 3 de Mayo de 2023
You could use ARRAYFUN to iterate over the elements of a structure (but this will be slower than a well-written loop):
file = struct('dist',{1:3,4:6,7:9})
out = arrayfun(@(s)s.dist(3),file)
This is very similar to the example shown here:
Más respuestas (0)
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!