How to access only the first element of the variables in a structure array as a vector?

조회 수: 47 (최근 30일)
Not sure I worded this question correctly, but I will try to explain.
I have a (1 x N) structure array (S) which contains the field "Location" like this:
%Pretend N = 3:
S(1).Location = [1 4];
S(2).Location = [4 15];
S(3).Location = [3 7];
I want to get a vector of the first entry of each "Location" variable, like this:
Location_1_Vector = [1 4 3]
Is there an efficient way to do this in one line without producing an intermediate variable?
The following do not work:
Location_1_Vector = [S(:).Location]; %Concatenates the Location variables together into [1 4 4 15 3 7]
Location_1_Vector = [S(:).Location(1)]; %Error: intermediate dot indexing produced comma separated ...
Of course, I can do it like this:
Location = reshape([S(:).Location],2,length(S));
Location_1_Vector = Location(1,:);
But I would prefer to avoid creating an intermediate "Location" variable with the additional clunkiness of "reshape".
Any help is appreciated.

채택된 답변

Paul
Paul 2023년 5월 17일
One option
S(1).Location = [1 4];
S(2).Location = [4 15];
S(3).Location = [3 7];
L = arrayfun(@(S) S.Location(1),S)
L = 1×3
1 4 3
  댓글 수: 1
Paul
Paul 2023년 5월 23일
Just realized the Question also asked for an efficient solution. arrayfun is one line and does not produce an intermediate variable, but not necessarily the most effiicient, at least in terms of run time.
S(1).Location = [1 4];
S(2).Location = [4 15];
S(3).Location = [3 7];
S = repmat(S,1,1000);
isequal(test1(S),test2(S),test3(S))
ans = logical
1
timeit(@() test1(S))
ans = 0.0058
timeit(@() test2(S))
ans = 1.2132e-04
timeit(@() test3(S))
ans = 7.1075e-04
function L = test1(S)
L = arrayfun(@(S) S.Location(1),S);
end
function L = test2(S)
Location = reshape([S(:).Location],2,length(S));
L = Location(1,:);
end
function L = test3(S)
L = nan(1,numel(S));
for ii = 1:numel(S)
L(ii) = S(ii).Location(1);
end
end

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by