Converting Struct Element Data Type

33 vues (au cours des 30 derniers jours)
SRance
SRance le 4 Nov 2020
Commenté : Vamsi le 8 Août 2023
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 commentaire
Rik
Rik le 4 Nov 2020
This sounds like you should write a recursive function.

Connectez-vous pour commenter.

Réponses (1)

Dave B
Dave B le 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 commentaire
Vamsi
Vamsi le 8 Août 2023
execution/app response time is increasing , i have used above way of calling the recurssive functions in app designer class

Connectez-vous pour commenter.

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by