- use a structure array (rather than a cell array containing structures)
- flatten the nested structures as much as possible.
Handling cells which contains structures
17 views (last 30 days)
Show older comments
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
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:
You could then likely use either of these approaches:
Answers (1)
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)) ...
}
% 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
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!