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
Ezio Antonio Mosciatti Urzua 2023 年 5 月 3 日
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 Center および File ExchangeStructures についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by