MATLAB Answers

0

Using dir() without changing directory?

Asked by Zeynab Mousavikhamene on 11 Oct 2019
Latest activity Commented on by Stephen Cobeldick on 12 Oct 2019
I need to find files that have dir(['*K1*.json']); in their names which are in a specific folder different from the matlab script folder. I prefere not to change directory because I will get error while running the script.
Is there any way to do so?

  6 Comments

@Geoff Hayes As i mentioned in the question, the folder containing *K1*.json is differnt from matlab running script and when I use dir(['/users/geoffh/someFolder/*K1*.json']) it will check all files in the folder containing the matlab script not in the folder containing K1.json files. I need a structure that can define the folder containing K1.json files.
Perhaps you did not understand:
The path specification "/users/geoffh/someFolder/" represents the full path to the folder that contains the files that you want to search. You need to substitude the actual path to your files.
If you specify a path in the 'dir' command, it will searth that specified folder.
"I prefere not to change directory because I will get error while running the script. "
Changing folders to access data files is a bad way to write code.
It is much better to use absolute/relative filenames, as the others have already commented.
"the folder containing *K1*.json is differnt from matlab running script... I need a structure that can define the folder containing K1.json files."
That is exactly what absolute/relative filenames are for:

Sign in to comment.

Tags

1 Answer

Answer by per isakson
on 12 Oct 2019

Use an absolute path rather than a relative path (as proposed in the comments). It's easier to get it right. Thus try
sad = dir( fullfile( 'c:', 'specific', 'folder', ['*K1*.json'] ) );

  0 Comments

Sign in to comment.