Handling cells which contains structures
Afficher commentaires plus anciens
Hello community,
I have a question how to nicely handle cells which contain a structure. What I have is a measuerement which is saved as cell. The cell has the following structure: cell.struct.struct.value. To access a specific value I use cell{n, 1}.struct_name.value_name, where n is an index and can go up to 5000. Usually I use this construct to extract the values: cell2mat(cellfun(@(s)s.struct_name.value_name,cell_name,'uni',0)).
In this case this doesn't work since the struct is empty for some indices. Any idea how to solve this without using a for loop?
Thanks Jeremy
1 commentaire
Often users places structures in cell arrays because they do not realize that structures are arrays too.
You could likely simplify your code:
- use a structure array (rather than a cell array containing structures)
- flatten the nested structures as much as possible.
You could then likely use either of these approaches:
Réponses (1)
% a cell array of structs with some stuff missing:
c = { ...
struct('field_1',struct('sub_field_1',1)) ...
struct('field_1',[]) ...
[] ...
struct('field_1',struct('sub_field_1',2)) ...
}
% the usual way gives an error in this case:
try
cell2mat(cellfun(@(s)s.field_1.sub_field_1,c,'uni',0))
catch ME
disp(ME.message);
end
% use a helper function that checks for the existence of fields:
cell2mat(cellfun(@(s)get_struct_value(s,'field_1','sub_field_1'),c,'uni',0))
% or a different helper function that puts NaNs where struct is empty, etc.:
cell2mat(cellfun(@(s)get_struct_value_with_NaN(s,'field_1','sub_field_1'),c,'uni',0))
function out = get_struct_value(s,struct_name,value_name)
if isfield(s,struct_name) && isfield(s.(struct_name),value_name)
out = s.(struct_name).(value_name);
else
out = []; % any empty struct or struct missing field returns empty array
end
end
function out = get_struct_value_with_NaN(s,struct_name,value_name)
if isfield(s,struct_name) && isfield(s.(struct_name),value_name)
out = s.(struct_name).(value_name);
else
out = NaN; % with appropriate place-holder value
end
end
1 commentaire
Jeremy Wayne
le 25 Nov 2022
Catégories
En savoir plus sur Structures dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!