concatenating file path to changing folders - matlab

I am somewhat new to MATLAB and am trying to set up a changing file path in a loop to go into a series of folders and grab image files from each folder. I'm not sure if the problem is with the concatenated parts of the path itself, or with the wildcard search I am using.
I've used similar changing file paths before that have worked, but this one is giving me a "Index exceeds matrix dimensions" error. I thought it was the '*' element that was problematic (similar concatenated paths have worked for me, but only when I specify a file extension or part of a file name), but I am trying to grab DICOM files that do not have any extension, which might make it difficult.
The line within the for loop is as follows:
inputs{1, crun} = cellstr(spm_select('FPList'[allinput,'T1Rawunzip',filesep,OrderForDicoms3{crun,1}],'*'));
I've tried different ways of specifying this--using spm_select, not using spm_select, using commas instead of filesep or vice versa, but nothing has worked.
Any advice would be very much appreciated.
(for reference:
crun is the counter the moves the loop forward, 'allinput' is a previously-specified path, OrderForDicoms3 is a .mat file with a list of folder names that are being individually concatenated to the path each time the loop runs)
Thanks!
-Victoria

I can tell you the most general approach of grabbing files from a folder. If you specify the input folder through uigetdir, then all the files can be grabbed using dir command:
folder = uigetdir;
files = dir(folder);
for i =1:length(files)
if(~files.isdir())
filename = fullfile(folder, files(i).name);
% ... read in the data %
end
end
You can always do it for multiple levels.

Related

delete files with numbered names in matlab directory

I'm new to matlab and I've wrote a code that implements the gamma function for image processing. I generate around 300 photos named '001.jpg' to '300.jpg' and then use ffmpeg to make a video.
In the end, I only need the video result and need a command to delete all the photos generated in the directory! is there a way to do that?
If you want to remove all .jpg files in the current directory you can use the delete command with a wildcard (*)
delete('*.jpg')
If the files live in a folder other than the current directory, you can specify the directory in this way.
folder = '/path/to/my/files';
delete(fullfile(folder, '*.jpg'))
If you want to limit it to just files that have number filenames, you could do something like the following
files = dir('*.jpg');
filenames = regexp({files.name}, '^[0-9]+\.jpg$', 'match', 'once');
filenames = cellstr(cat(1, filenames{:}));
delete(filenames{:})
Adding to Suever's answer (not allowed to comment yet):
Assuming you already know the names of the images you're creating, you could save your script a 'trip' to the folder and back by creating the filenames list yourself thus:
for i=1:numOfImages
filenames(i)={strcat(num2str(i),'.jpg')};
end
delete(filenames{:})

Renaming files in Matlab - movefile is creating folders instead of files

The current working directory contains a folder called 'dynamics_sorted' which contains 300 subfolders ('001', '002', etc), each of which contains some files, but only a single nifti (.nii) file.
The single nifti file from each of the numbered subfolders should be moved into 'dynamics_sorted_NIFTI' which is in the current working directory.
In the process, each nifti file should be renamed with the number of its parent folder.
The syntax for movefile suggests that when the arguments are both filenames then the file is renamed
http://uk.mathworks.com/help/matlab/ref/movefile.html#zmw57dd0e528520
for Ticker = 1:300;
FindNiftiFile = ['dynamics_sorted/',num2str(Ticker,'%03.0f'),'/*.nii'];
PutNiftiFile = ['dynamics_sorted_NIFTI/',num2str(Ticker,'%03.0f'),'.nii'];
movefile(FindNiftiFile,PutNiftiFile);
end
But this code does not rename the files, instead it keeps the filenames but places them into numbered folders.
Any advice as to where the error is?
I've found the answer - it's because of the wildcard used to find the source file. I'm guessing this leads Matlab to assume the source is not a single file, even when the wildcard is such that only a single file is eligible.

Open multiple subfolders within a loop

I have a folder named "Photos" that is a subfolder of the current directory. Inside that folder, there are four subfolders with names "Order1", "Order2",
"Order3", "Order4". I am trying to open these subfolders using a loop.
The following code is not working.
for i=1:4
current_path=pwd;
cd(current_path');
cd('Photos\Order%d',i);
end
There are a lot issues going on here at the same time.
The primary issue is that you are changing directories each time through the loop but you're also getting the value of the current directory (pwd) each time. The directory doesn't automatically reset to where you were when it goes back to the top of the loop. I think you expect current_path to be the folder you started in and be the same for all iterations.
You need to use sprintf or something similar to create your "OrderN" folder names. cd doesn't know what to do with the format specifier you're trying to use.
You should always use fullfile when concatenating file paths. Period.
You should use absolute paths when possible to remove the dependence upon the current directory.
Do you really need to change the working directory? If you're trying to load files within these folders, please consider using absolute file paths to the files themselves rather than changing folders.
If you are going to do this this way, please be sure to reset the path back to where it was at the end of the loop. There is nothing worse than running code and ending up in a directory that is different than where you were when you called it.
To actually make your code work, we could do something like this. But given all of my points above (specifically, 4-5), I would strongly consider a different approach.
startpath = pwd;
for k = 1:4
folder = fullfile(startpath, 'Photos', sprintf('Order%d', k));
cd(folder)
end
% Set the current directory to what it was before we started
cd(startpath)

How to read trc files from different directory in matlab

I have a program that reads data from .trc files. But as of now, it can only read the .trc files that are in the current directory i.e the MATLAB folder. If I want it to read a file, I have to copy the file in MATLAB folder. Is there a way I can move to different directories and choose another .trc file? I have tried using dir, uigetdir etc. but nothing seems to work!
It's pretty straightforward to filter results with the dir command with a file extension if you specify the folder to search with a wildcard character in place of the file name. You can then loop over the generated list of file names in the output structure (as shown) or whatever you need to do with those files.
folderName = 'C:\Path\To\Target\Folder\';
fileList = dir(strcat(folderName, '*.trc'));
for k = 1:length(fileList)
fileHere = fullfile(folderName, fileList(k).name);
% Do what you need with the files in here
end

Why do I need to change MATLAB path in order to read the files?

I am reading 50 files from a folder as follows:
list_of_files=dir(fullfile('/home/user/Desktop/MTP/schemes/o33smnpimp/data/', '*.dat'));
My problem is until & unless I have same exact folder opened as path in MATLAB path (one above the path window) this command won't work. What is the reason behind this? Actually there are multiple schemes and every time I need to run a particular scheme, I have to go to the data folder of that particular scheme. How can it be solved?
The issue is that you can get the list of files using the full path like you have but you ALSO need to specify the full path when you use it. For example, try changing your code to:
baseDir = '/home/user/Desktop/MTP/schemes/o33smnpimp/data/'; % <--- will use this twice
list_of_files=dir(fullfile(baseDir, '*.dat'));
for ind = 1:length(list_of_files)
myFilenameFull = fullfile(baseDir, list_of_files(ind).name); % <---- must use fullfile here too!
D1 = getData(myFilenameFull, 'stuff');
end