Converting Struct Element Data Type

27 次查看(过去 30 天)
SRance
SRance 2020-11-4
评论: Vamsi 2023-8-8
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 个)

Dave B
Dave B 2020-11-4
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 个评论
Vamsi
Vamsi 2023-8-8
execution/app response time is increasing , i have used above way of calling the recurssive functions in app designer class

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by