Unexpected result using cellfun with 'size' as first argument on string array
Afficher commentaires plus anciens
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 commentaires
Bruno Luong
le 21 Oct 2023
Modifié(e) : Bruno Luong
le 21 Oct 2023
the cyclist
le 21 Oct 2023
Modifié(e) : the cyclist
le 21 Oct 2023
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
le 21 Oct 2023
I had forgotten that one could even call cellfun with this syntax!
For good reason. It doesn't appear to be documented.
Bruno Luong
le 21 Oct 2023
Modifié(e) : Bruno Luong
le 21 Oct 2023
Réponses (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.
1 commentaire
Bruno Luong
le 21 Oct 2023
Catégories
En savoir plus sur Structures dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!