How to search through entirety of one field of a structure
13 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Mitchell Tillman
le 20 Jan 2020
Commenté : Stephen23
le 23 Fév 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 commentaire
Réponse acceptée
Walter Roberson
le 20 Jan 2020
filesListing = struct('name', lazyNames); %writing
ithName = {filesListing.name}; %reading
You can also
[filesListing(1:length(lazyNames)).name] = lazyNames{:};
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!