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 次查看(过去 30 天)
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 个评论
Rik
Rik 2023-5-3
移动:Rik 2023-5-3
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)
a = 2×3
1 2 3 4 5 6
You will need intermediate values anyway, so there is no gain or loss in doing what you already show.
Stephen23
Stephen23 2023-5-3
编辑:Stephen23 2023-5-3
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

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2023-5-3
编辑:Stephen23 2023-5-3
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})
file = 1×3 struct array with fields:
dist
out = arrayfun(@(s)s.dist(3),file)
out = 1×3
3 6 9
This is very similar to the example shown here:
  1 个评论
Ezio Antonio Mosciatti Urzua
Great, it works like a charm, thanks!
I guess I got confused with the nomenclature. I had a structure array, "file", with 25 structures, each of them with a field called "dist".

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by