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

94 views (last 30 days)
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.

Accepted Answer

Paul
Paul on 17 May 2023
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 Comment
Paul
Paul on 23 May 2023
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

Sign in to comment.

More Answers (0)

Categories

Find more on Structures 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!