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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by