How to search through entirety of one field of a structure

16 次查看(过去 30 天)
Hi all,
This is an issue I've been grappling with for a little while. It has workarounds, but I'd like to know if it can be done directly.
I often find myself with structs such as those that are returned from the "dir" command, where the struct is a nx1 struct array with several fields.
Let's say n = 10. My question is, how can I access all 10 names in that listing at once without using a for loop? And while I'm asking, is there also a way to write a 10x1 struct in this fashion without a for loop? I've been using workarounds using the for loop such as:
n=10;
lazyNames={'a','b','c','d','e','f','g','h','i','j'};
% Workaround iterative write solution
for i = 1:n
filesListing(i).name = lazyNames{i};
end
% Workaround iterative read solution
for i = 1:n
ithName{i} = filesListing(i).name;
end
But there has to be a more efficient way to perform this action, right?
The only way I've ever seen to write multiple entries into a struct at once is like this:
% Workaround matrix write solution
listing.lazyFieldName(1:10)=zeros(10,1);
And writing multiple at once doesn't seem to work at all in this fashion:
% Workaround matrix read solution
a(1:10)=listing.lazyFieldName(1:10);
But that's not quite the same structure format.
Thanks for your help!

采纳的回答

Walter Roberson
Walter Roberson 2020-1-20
filesListing = struct('name', lazyNames); %writing
ithName = {filesListing.name}; %reading
You can also
[filesListing(1:length(lazyNames)).name] = lazyNames{:};

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by