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

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

Related

MATLAB - Get current path and then use it to navigate to a different folder

I have a bunch of codes that are currently stored on my local machine. There are two folders, one called "Resources" and another called "src". There is one main script that needs to be run called "main.m" in "src" which calls files from "Resources".
If I copy this whole thing onto a new computer, the paths will change and MATLAB may not be able to find "Resources" anymore. I know that relative to "main.m", I need to go up one level and then into "Resources".
What is the best way of getting MATLAB to point to "Resources"?
I am currently trying along the lines of
P = mfilename('fullpath')
which gives the path for main.m. Now, I want to navigate from here, one folder up and then into "Resources". Or if there is a better way, please let me know.
Eventually, I want to extend it to work for multiple folders "Resources1", "Resources2" etc. so MATLAB needs to be able to navigate to the right folder.
You can get it like:
fullfile(fileparts(mfilename('fullpath')), '..', 'Resources');
Explanation:
mfilename('fullpath') will return the full path and name of the
M-file in which the call occurs, without the extension
fileparts will return the path of the passed file (only the containing directory)
fullfile will build the full directory specification from the folder names passed (Note: '..' always means the parent directory)
Based on this it is quite simple to write a function that gets the sibling directory of the directory containing the file:
getSiblingOfParentDirectory.m
function siblingDirPath = getSiblingOfParentDirectory(filepath, siblingDirName)
siblingDirPath = fullfile(fileparts(filepath), '..', siblingDirName);
end
then to use it in an M-file:
for i = 1:3
disp(getSiblingOfParentDirectory(mfilename('fullpath'), ['Resources', num2str(i)]));
end
Sample output:
D:\pathtest\Resources1
D:\pathtest\Resources2
D:\pathtest\Resources3
You can try the following:
ResourcesFolder = strrep(mfilename('fullpath'), 'src\main', 'Resources');
addpath(ResourcesFolder);
%%Your code here where you need those files
rmpath(ResourcesFolder);
Which is fully dependant on the names of your folders & files of course. Basically "addpath" enables you to access the files in the mentioned directory by adding it to the search path, and "rmpath" does the exact opposite.
Also, if you literally want to navigate to a folder present on one level up, you can execute the following:
cd ..\Resources
Which goes one level up, searches for the folder 'Resources', then changes the current directory to that folder .

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)

Matlab switch libraries

I have download some libraries for Matlab. Unfortunately one of those libraries has the same name as one in the Matlab toolbox. So, when trying to call that downloaded library, Matlab calls its own. How can I solve this? Is there I way to 'switch' the path for an specific function?
You can temporarily add the folder my_files to the search path, run my_function in my_files, then restore the previous search path. To select which library is used first, just add to the top of PATH.
1) Grab your default path
p = path
2 ) Add c:/matlab/myfiles to the TOP of the search path.
addpath('c:/matlab/myfiles')
2) OR Add Folder to End of Search Path
addpath('c:/matlab/myfiles','-end')
Run you code
my_function
Restore Path
path(p)
So to run from libray A:
% Grab default path
p = path
% Search this folder first
addpath('c:/matlab/A')
% Run your code
my_function
%Restore Path
path(p)
If you have the same function names on different libraries you can just define the library first.
for instance:
duration/max(); % uses max from duration toolbox/libary
max(); % uses standard max.
So you could also just rename you library folder name and select which one you want to use.

Access data files from subfolder of current script directory

I have been working on MATLAB scripts.
Basically, I have a lot of functions and data files (collectively known as kernels):
I want to organize it a little bit.
The idea is
to create a subfolder named functions and save all functions in it.
Another kernels and save all data kernel files in it.
Later by adding these paths at runtime, all the scripts should be able to access these functions and kernels without giving the full path to them, i.e. The script should search it in the subfodlers too.
Applying addpath(genpath(pwd)); worked for functions but it couldn't access kernel files
e.g. What if I want to access file named naif0010.tls inside subfolder kernels.
It didn't work. Any suggestions.
Example:
% Add the current script directory and subfolders to search path
addpath(genpath(pwd));
% Load NASA Spice (mice) to the script here
% add MICE reference path to MATLAB
addpath('C:\Program Files\MATLAB\R2012b\extern\mice\src\mice');
addpath('C:\Program Files\MATLAB\R2012b\extern\mice\lib');
% Load leap second kernel
% If the leapsecond kernel is placed in script directory
% This file is present in pwd/kernel/naif0010.tls
cspice_furnsh('naif0010.tls');
There are a couple of things to keep in mind. First, your current working directory (pwd) is in the Matlab path by default, so you don't usually need to explicitly call addpath in order to use scripts, functions, or data files there.
Also, in many cases you can access files by providing a relative path rather than an absolute path. In your case, this would look like
cspice_furnsh('kernels/naif0010.tls')
I solved it with some work around which I know is not the correct answer but for now I can go ahead....
addpath(genpath(pwd));
% Basically just forming full path of the data file
leapSecondsFile = fullfile(pwd,'kernels','naif0010.tls');
cspice_furnsh(leapSecondsFile);
Still waiting for correct answer or suggestions :-)
Update:
Thanks nispio's comment above, The correct way is :
% Load current directory and subfolders
addpath(genpath(pwd)); % This is not necessary
cspice_furnsh('kernels\naif0010.tls');

concatenating file path to changing folders

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.