Unexpected result using cellfun with 'size' as first argument on string array
古いコメントを表示
The title of the topic says it all, but here is the result I would not expected.
Is this behaviour intended? or is it a bug?
s=["1"; "2"; "3"]
size(s,1)
cellfun(@(s) size(s,1), {s}) % correct
cellfun('size', {s}, 1) % this returns 1, that is not as I expected (not correct), 3 is correct answer
4 件のコメント
I had forgotten that one could even call cellfun with this syntax!
FYI, works as you would expect on a 3x1 character array as well:
s = ['1'; '2'; '3'];
size(s,1)
cellfun(@(s) size(s,1), {s})
cellfun('size', {s}, 1)
Matt J
2023 年 10 月 21 日
I had forgotten that one could even call cellfun with this syntax!
For good reason. It doesn't appear to be documented.
Bruno Luong
2023 年 10 月 21 日
編集済み: Bruno Luong
2023 年 10 月 21 日
回答 (1 件)
Not a bug.
On the documentation page for the cellfun function, in the description of the func input argument, there is a section titled "Backward Compatibility". The relevant parts of that section: "If you specify a function name rather than a function handle:
- cellfun does not call any overloaded versions of the function.
- The size and isclass functions require additional inputs to the cellfun function"
Essentially, in that case cellfun will call the built-in size function rather than the string class's overload.
s=["1"; "2"; "3"]
which size(s) % string overload
which size({s}) % built-in function
cellfun(@size, {s}, 'UniformOutput', false) % calls string overload
cellfun('size', {s}, 1) % calls built-in
builtin('size', s)
Internally, a string array is a scalar object. It just tells MATLAB (via its size overload) that it has the size of its contents.
This is why I don't recommend calling cellfun (or arrayfun or structfun) with the name of the function to be applied. Use a function handle (could be anonymous) instead.
カテゴリ
ヘルプ センター および File Exchange で Structures についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!