Why does dir .name output have two answers but numel reports only one element?
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Daniel Bridges
el 26 de En. de 2018
>> NoPtfolders.name
ans =
'1'
ans =
'2'
>> numel(NoPtfolders.name)
ans =
1
NoPtFolder is a 2x1 structure. What is NoPtFolders.name if not a 2x1 cell array? Why does numel report only one element?
(This result follows Walter Roberson's instruction to remove the current and parent directory listings.)
1 comentario
Respuesta aceptada
Stephen23
el 26 de En. de 2018
Editada: Stephen23
el 26 de En. de 2018
Here is an in-depth discussion of exactly this behavior:
In summary, it is because the number of outputs is demand-driven, and the outer function numel demands exactly one output from the inner function subsref. The inner function subsref (called by a convenience operator) converted your non-scalar structure NoPtfolders into a comma-separated list of scalar structures, but numel only demands one argument of that list... which is hence one single scalar structure.
Here is a visual interpretation: the convenience operator
S.field
actually calls the function subsref, which returns
S(1).field, S(2).field, s(3).field, ...
and because the inner function always supplies exactly one output argument as an input argument to the outer function then your call is simply equivalent to
numel(NoPtfolders(1).name)
which will be scalar... unless NoPtfolders is empty in which case there are no outputs from subsref and so numel gets no inputs and MATLAB throws an error.
It is not clear what you want to test for, so I cannot suggest what you should be doing. Perhaps
numel(NoPtfolders)
is what you want?
Note that MATLAB always has a demand-driven number of outputs: you can call any function with from 0 to the maximum number of output arguments, and MATLAB will supply as many as you demand from the function. An outer function always demands one argument from an inner function (for reasons discussed in the link at the top of this answer).
6 comentarios
Stephen23
el 27 de En. de 2018
@Daniel Bridges: high-level functions like num2str or str2double are very convenient, but inside they are just wrappers around calls to low-level operators like sprintf and sscanf, with some fancy input checking and lots of processing to automatically handle different input sizes/classes/...
Using low-level operators gives you direct control over the conversion (which may be an advantage or a disadvantage, depending on the situation), and by removing the wrapper are also significantly faster.
Use whichever one makes your code clearest for you.
Más respuestas (0)
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!