How to access only the first element of the variables in a structure array as a vector?
조회 수: 93 (최근 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.
댓글 수: 0
채택된 답변
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)
댓글 수: 1
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))
timeit(@() test1(S))
timeit(@() test2(S))
timeit(@() test3(S))
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 Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!