Filter löschen
Filter löschen

reading the file from different directories

26 Ansichten (letzte 30 Tage)
Rajesh
Rajesh am 26 Mär. 2024
How to read a file_2 of different directory from the file_1 of the working directory without adding the full path of file_2 in file_1?
  5 Kommentare
Dyuman Joshi
Dyuman Joshi am 26 Mär. 2024
You would have to provide the path to the file(s).
Or (if possible and more conveniant,) directly provide the file.
(These are the only possibilites I could come up with now, I'll update if some other ideas come up)
If the folder structure is not available, then, would using dir to get the folder structure work or not?
Stephen23
Stephen23 am 26 Mär. 2024
"What if I share my local repo to some other matlab user, where my folder structure is not available? "
Let them specify the location of their own data files.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

prabhat kumar sharma
prabhat kumar sharma am 1 Apr. 2024
Hi Rajesh,
I Understand you are looking for a method to use a file that is not in the current directory within another file.
Here are several effective methods you might consider exploring.
1.If you know the relative location of file_2 with respect to file_1, you can construct the path dynamically using fullfile. This method is useful when the directory structure is consistent but the absolute path may vary.
relativePath = fullfile('..', 'otherDirectory', 'file_2.ext');
data = readmatrix(relativePath); % Use the appropriate function for your file type
2. Allow users to specify the path. This method is particularly useful when sharing your code with others who may have a different directory structure.
userPath = input('Enter the path to file_2: ', 's');
data = readmatrix(userPath);
3. For a more interactive approach, especially in desktop environments, use uigetfile to open a file dialog that allows users to navigate to and select file_2.
[file, path] = uigetfile('*.*', 'Select file_2');
if isequal(file, 0)
disp('User selected Cancel');
else
fullPath = fullfile(path, file);
data = readmatrix(fullPath);
end
4. For projects shared across multiple users, consider using a configuration file that specifies paths. Users can edit this file to set their paths.
config.txt
path_to_file_2 = /path/to/file_2.ext
MATLAB Code
config = readtable('config.txt', 'ReadVariableNames', false, 'Delimiter', '=');
file2Path = strtrim(config{1,2}{1});
data = readmatrix(file2Path);
I hope it helps to resolve your issue.

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by