Indexing multiple values of an array of structures with a field that varies in length

조회 수: 7(최근 30일)
John Petersen 2014년 11월 26일
답변: Geoff Hayes 2014년 11월 26일
I have an array of structures, A. Each structure has a field 'vec'. Each 'vec' is a vector, but the length of the vector can vary with the index into A. So
length( A(i).vec ) = n
length( A(j).vec ) = m
I want to grab the last number of each of these vectors and place them in an array. The idea is something like
x = A(:).vec(end);
but of course that doesn't work.

댓글을 달려면 로그인하십시오.

채택된 답변

Geoff Hayes 2014년 11월 26일
John - why not use arrayfun to grab the last element of each structure in your array A. Something like
lastElements = arrayfun(@(x)x.vec(end),A);
This seems to work for the following example
% randomly choose the lengths of 100 vectors
vecLengths = randi(42,100,1);
% create A
A = [];
for k=1:length(vecLengths)
A(k).vec = randi(255,1,vecLengths(k));
end
% get the last element from each vector
lastElements = arrayfun(@(x)x.vec(end),A);

댓글을 달려면 로그인하십시오.

범주

Find more on Data Types in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by