error in using cellfun

2 ビュー (過去 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 Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by