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!