Matlab下标索引错误,以完美的交互方式运行

时间:2017-05-31 19:04:53

标签: matlab

我正在研究一个matlab脚本,该脚本以递归方式循环遍历目录并尝试查找某种类型的所有文件。我正在使用数组作为一种堆栈。

该行

dirstack{end + 1} = filesInCurrentDir(i);

失败。但是,如果我使用dbstop if error并逐行运行完全相同的行,则可以正常运行。

如果我将索引预先分配给length(dirstack) + 1

,它也会失败

这是否有理由在脚本环境中不起作用,但它会在交互式环境中起作用?

最低工作示例:

DIR='.';
dirstack{1} = DIR;
while length(dirstack) ~= 0 %loop while there's still directories to look for
    curdir = dirstack{1}; %the working directory is popped off the top of the stack
    dirstack{1} = []; %delete the top element, finishing the pop operation
    filesInCurrentDir = dir(curdir);
    for i=3:length(filesInCurrentDir) % start at 3, dir returns 1:. 2:.. and we don't want those
        if filesInCurrentDir(i).isdir; %if this is a directory
            dirstack{end+1} = filesInCurrentDir(i);
        elseif strcmp(filesInCurrentDir(i).name(end+[-3:0], '.jpg')) == 1 %if it's a psdata file
            files{end+1} = [curdir, filesep, filesInCurrentDir(i_.name)];   
        end
    end

end

1 个答案:

答案 0 :(得分:0)

这就是我在当前文件夹及其子文件夹下获取所有.jpg文件的方法:

dirs = genpath(pwd); % dir with subfolders
dirs = strsplit(dirs, pathsep); % in cellstr for each dir
files = {};
for i = 1:numel(dirs)
    curdir = [dirs{i} filesep];
    foo = dir([curdir '*.jpg']); % all jpg files
    foo([foo.isdir]) = []; % just in case .jpg is folder name
    foo = strcat(curdir, {foo.name}); % full file names
    files = [files foo]; % cell growing
end

现在回到你的问题。您的代码中有几处错误。您可以与我更正的代码进行比较,并在代码中查看我的评论:

dirstack = {pwd}; % ensure init dirstack to current dir
files = {};
while length(dirstack) ~= 0 % better ~isempty(dirstack)
    curdir = dirstack{1};
    dirstack(1) = []; % dirstack{1} = [] sets first cell to [], wont remove the cell as you want
    filesInCurrentDir = dir(curdir);
    for i=3:length(filesInCurrentDir) % this works for Windows, but may not be safe to always skip first two
        if filesInCurrentDir(i).isdir
            dirstack{end+1} = filesInCurrentDir(i);
        elseif strcmp(filesInCurrentDir(i).name(end+[-3:0]), '.jpg') == 1 % had error here
            files{end+1} = [curdir, filesep, filesInCurrentDir(i).name]; % had error here
        end
    end

end