Anudocs
Anudocs

Reputation: 686

cellfun error : Input #2 expected to be a cell array, was double instead

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.

Upvotes: 0

Views: 1918

Answers (2)

FangQ
FangQ

Reputation: 1544

for the 3rd call, the struct s you created is called a "Nonscalar Struct Array", because your f2 element is a cell array of non-scalar elements. Aside from the solution provided by @Sandar, you can also do

x=cellfun(@numel, {s(:).f2})

Upvotes: 0

Sardar Usama
Sardar Usama

Reputation: 19689

The first line of cellfun documentation says (emphasis mine):

Apply function to each cell in cell array.

You don't have cell arrays in your second and third usage of cellfun and hence those do not work.


In your second usage of cellfun i.e x = cellfun(@(u) numel(u), s.f2);
s.f2 returns a comma separated list. To get the same result using cellfun, you can concatenate the comma separated list in a cell array and then cellfun like this:

x = cellfun(@(u) numel(u), {s.f2});

In the third usage of cellfun, you are inputting a vector structure. In this case to get the same result, you can apply arrayfun more conveniently like this:

x = arrayfun(@(u) numel([u.f2]), s);

Upvotes: 1

Related Questions