Converting Struct Element Data Type

33 ビュー (過去 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 件のコメント
Rik
Rik 2020 年 11 月 4 日
This sounds like you should write a recursive function.

サインインしてコメントする。

回答 (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 Center および File ExchangeStructures についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by