Understanding the structfun() or cellfun() commands
이전 댓글 표시
Dear All,
I want to avoid the use of for loops by using the structfun() and cellfun() commands.
I have a folder with a bunch of "nnn_M.csv" files, where the "nnn" prefix corresponds to numbering of the files, and the "_M" suffix being constant for all files. My goal is to create a double array of the "nnn" values.
The code I currently use with a for loop: (Works)
Files = dir('*.csv'); % Create the structure of file descriptions (name,datenum,...)
N = length(Files); % Determind # of files for the for loop
for ii = 1:N
FileNames{ii} = Files(ii).name; % Create cell array of the file names
nnn(ii) = sscanf(FileNames{ii},'%d_M'); % Create double array of file prefixes
end
This is the code without a for loop: (Does not work)
Files = dir('*.csv'); % Create the structure of file descriptions (name,datenum,...)
FileNames = structfun(@(x) Files(x).name, Files); % Create cell array of the file names
nnn = cellfun(@(x) sscanf(FileNames{x},'%d_M'),FileNames); % Create double array of file prefixes
The 2nd and 3rd lines give me errors, repectively:
Error using structfun
Inputs to STRUCTFUN must be scalar structures.
% and
Index exceeds the number of array elements (14).
Error in @(x)sscanf(FileNames{x},'%dK')
% When using the correct 'FileNames' the for loop gives
% There are 14 *.csv files in the folder
I welcome all suggestions you may have. Thank you for helping me understand these functions!
Cheers,
-Jackson
채택된 답변
추가 답변 (1개)
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!