Applying function only to certain files in directory
Show older comments
Hi, I have the following code, which applies the function 'load_nii' to files from the current directory which I select manually with the variables k and l:
currentFolder = pwd;
listing = dir;
allDirNames = { listing.name };
dirLA =~ [ listing.isdir ];
dirLA(1:2) = 0;
dirNames = allDirNames(dirLA);
% set k, l to choose which files to convert
k = 3;
l = 182;
% convert Niftis to Mat-Files
for idx = k:l
foo(idx) = load_nii(allDirNames{idx});
betas{idx-(k-1)} = foo(idx).img;
end
What I want however is that the function load_nii is automatically applied to all files which start with certain strings (e.g. "results"), such that I don't have to set the variables k and l manually. How can I do that?
Thanks
4 Comments
Guillaume
on 10 Apr 2017
Not answering the question since it's already been answered, but commenting on your code:
dirLA(1:2) = 0;
I presume this is to remove the '.' and '..' that matlab stupidly returns. This assumes that these two directories are always the first two in the list. This is a dangerous assumption to make. The listing is returned alphabetically so any directory that starts with any of !"#$%&'()*+,- will appear before the . and ... You may not have such directories, but they are allowed by most OSes.
Much safer is not to rely on any ordering and use
dirLA(ismember(allDirNames, {'.', '..'})) = false;
dpb
on 10 Apr 2017
Just a note that if use the name search then the directories won't show up altho the extra pair of suspenders besides the belt never hurts...
Guillaume
on 10 Apr 2017
Oh yes, with the solution proposed, there's no need to filter the directories anyway.
My comment was more generic in case such code (directory listing) is used for something else where file filtering does not apply.
I don't know why mathworks decided to return these two useless entries other than for the sake of matching the antiquated behaviour of dos dir.
MiauMiau
on 11 Apr 2017
Accepted Answer
More Answers (0)
Categories
Find more on Texas Instruments C2000 Processors in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!