Handling cells which contains structures

10 vues (au cours des 30 derniers jours)
Jeremy Wayne
Jeremy Wayne le 9 Nov 2022
Modifié(e) : Stephen23 le 25 Nov 2022
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
Stephen23
Stephen23 le 25 Nov 2022
Modifié(e) : Stephen23 le 25 Nov 2022
Often users places structures in cell arrays because they do not realize that structures are arrays too.
You could likely simplify your code:
  1. use a structure array (rather than a cell array containing structures)
  2. flatten the nested structures as much as possible.
You could then likely use either of these approaches:

Connectez-vous pour commenter.

Réponses (1)

Voss
Voss le 9 Nov 2022
% 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)) ...
}
c = 1×4 cell array
{1×1 struct} {1×1 struct} {0×0 double} {1×1 struct}
% 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
Dot indexing is not supported for variables of this type.
% 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))
ans = 1×2
1 2
% 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))
ans = 1×4
1 NaN NaN 2
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
Jeremy Wayne le 25 Nov 2022
Thanks for the feedback.
Unfortunately it didn't work out for me. So what I just did a loop and replaced all empty structs with a dummy struct.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Tags

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by