Converting Struct Element Data Type
27 views (last 30 days)
Show older comments
I am trying to convert to all the field of a nested struct to single precision.
Having noted a similar question on StackOverflow (https://stackoverflow.com/questions/29244516/how-to-convert-datatype-of-all-fields-of-struct-in-matlab-to-double/29244686#29244686), the general solution below works if the fields are only one level, however I have a few nested a nested struct - i.e. struct has elements of variables, arrays and structs which is sometime repeated for multiple levels.
mystruct = cell2struct(cellfun(@single,struct2cell(mystruct),'uni',false),fieldnames(mystruct),1)
Is there a way to list the fields of a struct such that I can apply the method above in a for loop?
My thought is if a have a struct with fields a, b and c, is that I can this method to each of those fields in turn and go to deeper levels if any are structs.
1 Comment
Answers (1)
Dave B
on 4 Nov 2020
Hi SRance
To list the fields for a struct, you can use the fieldnames function which you can see in that big line of code. I agree that it might be easier to think about the recursive nature of the problem with a vectorized approach. Here's a demo function which handles the simple cases (but note the comment, you may want to check for other non-struct types).
function somestruct=convert2Single(somestruct)
% Retrieve a list of fields:
fields=fieldnames(somestruct);
% Loop over fields:
for i = 1:numel(fields)
if isstruct(somestruct.(fields{i}))
% If another struct is encountered, recurse.
somestruct.(fields{i})=convert2Single(somestruct.(fields{i}));
else
% Note: Consider other (non-struct) types, if you have a char for
% instance it's going to be cast to single...do you want to check
% isnumeric? or isdouble?
% Cast this field to single
somestruct.(fields{i})=single(somestruct.(fields{i}));
end
end
end
1 Comment
Vamsi
on 8 Aug 2023
execution/app response time is increasing , i have used above way of calling the recurssive functions in app designer class
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!