How to search through entirety of one field of a structure
13 views (last 30 days)
Show older comments
Mitchell Tillman
on 20 Jan 2020
Commented: Stephen23
on 23 Feb 2022
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!
1 Comment
Accepted Answer
Walter Roberson
on 20 Jan 2020
filesListing = struct('name', lazyNames); %writing
ithName = {filesListing.name}; %reading
You can also
[filesListing(1:length(lazyNames)).name] = lazyNames{:};
0 Comments
More Answers (0)
See Also
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!