首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Matlab Subscript索引错误,完美交互运行

Matlab Subscript索引错误,完美交互运行
EN

Stack Overflow用户
提问于 2017-06-01 03:04:53
回答 1查看 25关注 0票数 0

我正在编写一个matlab脚本,该脚本递归地遍历一个目录,并尝试查找特定类型的所有文件。我使用一个数组作为一种堆栈。

这条线

代码语言:javascript
复制
dirstack{end + 1} = filesInCurrentDir(i);

失败。但是,如果我使用dbstop if error并逐字手动运行完全相同的行,它就可以很好地工作。

如果我为length(dirstack) + 1预先分配了一个索引,它也会失败

这在脚本环境中不起作用,但在交互环境中却能起作用,这有什么原因吗?

最小工作示例:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2017-06-01 03:50:19

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

代码语言:javascript
复制
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

现在回到你的问题上。代码中有几个地方有错误。您可以与我更正的代码进行比较,并检查我在代码中的注释:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44292836

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档