Why does not string(f.name) work, f = dir(folder)?
7 次查看(过去 30 天)
显示 更早的评论
I want to do something to, like split, the filenames in a folder. I first use dir( ) to get the contents of the folder.
folder = "~/Documents"
f = dir(folder). % f is a structure
Though f.name looks like a cell array, however,
string(f.name)
% Error using string No constructor 'string'
% with matching signature found.'
I don't understand what that means. Your answer will help me learn to code with correct understanding.
cellfun(@string, f.name)
% Error using cellfun
% Input #2 expected to be a cell array, was char instead.
Does that mean f.name send its element to @string one by one, and cellfun expect to receive the whole cell array?
On the other hand, if I enclose f.name with { },
string({f.name}) % no error message
0 个评论
采纳的回答
Stephen23
2022-8-17
编辑:Stephen23
2022-8-17
"Why does not string(f.name) work, f = dir(folder)?"
Dot indexing into the structure f
f.name
generates a comma-separated list:
In the general case, this code
string(f.name)
will not work because it generates this comma-separated list:
string(f(1).name, f(2).name, .., f(end).name)
and STRING() is not defined for multiple input arguments like that. So clearly that syntax will not work.
"Though f.name looks like a cell array..."
It isn't a cell array, it is a comma-separated list. In contrast, this code:
{f.name}
generates one cell array from the comma-separated list, i.e. is equivalent to this:
{f(1).name, f(2).name, .., f(end).name}
and STRING() has no problem converting that cell array to a string array.
2 个评论
Stephen23
2022-8-17
编辑:Stephen23
2022-8-17
"It seems to resemble what generator in Python does.
The whole point of the Python generator is that the elements do not exist in memory prior to being generated, but with the comma-separated list the elements already existed in memory and are not generated on the fly. The Python equivalent would be the asterisk operators, e.g. unpacking tuples and input arguments.
"After an element is processed, it is not stored in memory."
That rather depends on you, not on the comma-separated list syntax. You are welcome to discard the elements or store them (as my example with the cell array shows), or supply them as input arguments to any other suitable function/operator of your choice.
更多回答(2 个)
Steven Lord
2022-8-17
filename = fullfile(matlabroot, 'toolbox', 'matlab', 'elfun', '*.m');
D = dir(filename)
s = string({D.name});
Now you can operate on the elements of s.
s(1:4)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!