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
2020-1-20
filesListing = struct('name', lazyNames); %writing
ithName = {filesListing.name}; %reading
You can also
[filesListing(1:length(lazyNames)).name] = lazyNames{:};
0 个评论
更多回答(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!