Converting Struct Element Data Type
조회 수: 23 (최근 30일)
이전 댓글 표시
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
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
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 Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!