Matlab下标索引错误,交互运行良好

Matlab下标索引错误,交互运行良好,matlab,Matlab,我正在编写一个matlab脚本,该脚本递归地遍历一个目录,并尝试查找特定类型的所有文件。我使用数组作为堆栈的一种 线路 dirstack{end + 1} = filesInCurrentDir(i); 失败了。但是,如果我使用dbstop if error并手动逐字地运行完全相同的行,则效果很好 如果我将索引预先分配给length(dirstack)+1 这在脚本环境中不起作用,但在交互环境中起作用,有什么原因吗 最低工作示例: DIR='.'; dirstack{1} = DIR; whi

我正在编写一个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

以下是获取当前文件夹及其子文件夹下所有.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

谢谢,我要试试新方法。我还是不明白为什么我会有原始版本?特别是因为确切的代码行以交互方式正确运行,而且看起来您没有发现任何问题?我在代码的注释中解释了错误。一个主要错误是在删除单元格元素时使用dirstack(1)而不是dirstack{1}。其他的像是语法错误或打字错误(我用“had error here”标记)。错误消息可能是由于语法错误造成的。所以我不相信你的最低限度的例子一行一行地起作用。