How to remove struct fields of a specific type

조회 수: 12 (최근 30일)
Joe Gibbs
Joe Gibbs 2023년 7월 7일
댓글: engdancili 2024년 9월 18일
I have a struct that contains data of various formats including further structs and instances of class objects. I would like to remove all fields that are of a specific type without needing to use their field names.
For example, the trackingScenario struct contains a varying number of "Tracker" objects that I would like to remove if desired. I have posted an example of the struct below.
struct with fields:
configData: [1×1 struct]
simulation: [1×1 struct]
Platform_1: [1×1 struct]
Platform_2: [1×1 struct]
Platform_3: [1×1 struct]
Platform_4: [1×1 struct]
Target_1: [1×1 struct]
Target_2: [1×1 struct]
new_test_tracker2: [1×1 Tracker]
The desired output would be the struct without the "Tracker" field. This has stumped me so thanks in advance!

채택된 답변

Paul
Paul 2023년 7월 7일
The function class can be used in a loop over the fieldnames to identify the fields to be removed with rmfield.
s.w = int32(0);
s.x = 1;
s.y = 2;
s.z = int32(3);
s
s = struct with fields:
w: 0 x: 1 y: 2 z: 3
% remove the int32 fields
fnames = fieldnames(s);
for ii = 1:numel(fnames)
if string(class(s.(fnames{ii}))) == "int32"
s = rmfield(s,fnames{ii});
end
end
s
s = struct with fields:
x: 1 y: 2
The function isa might also do the job of identifying the field to be removed, depending on the class hierarchy and if you want to remove objects basedon their superclass.
  댓글 수: 1
engdancili
engdancili 2024년 9월 18일
Very useful. If the struct has several nested fields, one can exploit recursive functions to get the job done. Here is my (GitHub CoPilot) edit to remove function handles from a struct.
function s = removeFunctionHandles(s)
fnames = fieldnames(s);
for ii = 1:numel(fnames)
if isstruct(s.(fnames{ii}))
s.(fnames{ii}) = removeFunctionHandles(s.(fnames{ii}));
elseif isa(s.(fnames{ii}), 'function_handle')
s = rmfield(s, fnames{ii});
end
end
end
Off topic: Simulink allows you to work with struct variables, but if a struct is passed to a MATLAB function block (as a not tunable parameter) it will throws you an error since:
"You can use function handles in a MATLAB Function block. You cannot use function handles for Simulink® signals, parameters, or data store memory." From: Function Handle Limitations for Code Generation

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

sushma swaraj
sushma swaraj 2023년 7월 7일
Hi,
You can use the rmfield function to remove a specified field from structure array.
Refer to this documentation :
Hope it helps!

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by