image thumbnail

Apply a function to a specific field of a structure

by

 

This function searches in a structure, and applies a function to all occurrences of a field.

apply_func_on_all_fields_with_name.m
function temp_structure = apply_func_on_all_fields_with_name(temp_structure, field_name, func_id, data_bag)
% This function searches in the fields of a structure, and applies a given
% function to all occurrences of a specific field.
%
%  September 30th, 2009, By Reza Farrahi Moghaddam, Synchromedia Lab, ETS, Montreal, Canada
%
% USAGE:
% temp_structure = apply_func_on_all_fields_with_name(temp_structure, field_name, func_id, data_bag);
% where
%   temp_structure: The input structure
%   field_name: The target field name
%   func_id: The function that will be applied to the target fields
%   data_bag: (optional) A basket/bag to pass the parameters to the func_id
% Outputs
%   temp_structure: The output structure
%
% Below, an example is provided.
%   sample_struct.check = 5;
%   sample_struct.level.check = 4;
%   sample_struct.level.other = 'a';
%   sample_struct.level.another.test = 7;
%   sample_struct.level.another.check = -2;
%   % apply the 'sqrt' function to the 'check' fields of the structure
%   sample_struct = apply_func_on_all_fields_with_name(sample_struct, 'check', @sqrt);
%
%
%


%
if (nargin > 3)
    temp_tail = ', data_bag);';
else
    temp_tail = ');';
end

%
set_of_fields = fieldnames(temp_structure);
size_of_fileds_set = size(set_of_fields, 1);
% level 0
if (isfield(temp_structure, field_name))
    eval(['temp_structure.', field_name, ' = func_id(temp_structure.', field_name, temp_tail]);
end
%
for temp_up_field_name_label =1:size_of_fileds_set
    temp_up_field_name = set_of_fields{temp_up_field_name_label};
    temp_sub_structure = eval(['temp_structure.', temp_up_field_name,';']);
    %
    if (isfield(temp_sub_structure, field_name))
        eval(['temp_sub_structure.', field_name, ' = func_id(temp_sub_structure.', field_name, temp_tail]);
    end
    if (isstruct(temp_sub_structure))
        if (nargin > 3)
            temp_sub_structure = apply_func_on_all_fields_with_name(temp_sub_structure, field_name, func_id, data_bag);
        else
            temp_sub_structure = apply_func_on_all_fields_with_name(temp_sub_structure, field_name, func_id);
        end
    end
    eval(['temp_structure.', temp_up_field_name, ' = temp_sub_structure;']);
end


end


Contact us