Handling cells which contains structures

17 views (last 30 days)
Jeremy Wayne
Jeremy Wayne on 9 Nov 2022
Edited: Stephen23 on 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 Comment
Stephen23
Stephen23 on 25 Nov 2022
Edited: Stephen23 on 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:

Sign in to comment.

Answers (1)

Voss
Voss on 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 Comment
Jeremy Wayne
Jeremy Wayne on 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.

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Tags

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!