error in using cellfun
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
James Tursa
2020-4-7
编辑:James Tursa
2020-4-7
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!