MATLAB: Error in using cellfun

cell arraycellfunstruct

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);

Best Answer

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.