error in using cellfun

조회 수: 3 (최근 30일)
anubhav jhalani
anubhav jhalani 2020년 4월 7일
댓글: Stephen23 2020년 4월 7일
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);

채택된 답변

James Tursa
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
Stephen23
Stephen23 2020년 4월 7일
Simpler in one step:
s = struct(... field2,{value2},...)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by