error in using cellfun
4 views (last 30 days)
Show older comments
field1 = 'f1'; value1 = [1 2];
field2 = 'f2'; value2 = {1, 2, 32, 'text'};
field3 = 'f3'; value3 = [pi pi.^2];
field4 = 'f4'; value4 = [1 2 3];
s = struct(field1,value1,field2,value2,field3,value3,field4,value4);
x = cellfun(@(u) numel(u), value2); %%% WORKS FINE
x = cellfun(@(u) numel(u), s.f2); %%%% THROWS ERROR
x = cellfun(@(u) numel(u.f2), s); %%%% THROWS ERROR
Can someone give explaination why the last 2 lines throws error? The error is :
Error using cellfun
Input #2 expected to be a cell array, was double instead.
Error in test (line 11)
x = cellfun(@(u) numel(u), s.f2);
0 Comments
Accepted Answer
James Tursa
on 7 Apr 2020
Edited: James Tursa
on 7 Apr 2020
This is a limitation of the struct( ) function when fed a cell array. If you examine s you will see it is not what you wanted.
You could do it in two steps
>> s = struct(field1,value1,field2,[],field3,value3,field4,value4);
>> s.(field2) = value2
s =
struct with fields:
f1: [1 2]
f2: {[1] [2] [32] 'text'}
f3: [3.1416 9.8696]
f4: [1 2 3]
>> cellfun(@(u) numel(u), value2)
ans =
1 1 1 4
>> cellfun(@(u) numel(u), s.f2)
ans =
1 1 1 4
The last one should throw an error because s is not a cell array
>> cellfun(@(u) numel(u.f2), s)
Error using cellfun
Input #2 expected to be a cell array, was struct instead.
1 Comment
Stephen23
on 7 Apr 2020
Simpler in one step:
s = struct(... field2,{value2},...)
More Answers (0)
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!