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 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