Shahgee
Shahgee

Reputation: 3405

changing folder name, matlab

I want to set path for my text file programmatically. e.g.,

file = 'H:\user4\matlab\myfile.txt';
[pathstr, name, ext] = fileparts(file)

pathstr =    H:\user4\matlab

name =    myfile

ext =    .txt

I want to write all file in H:\user4\myfile. How can I get this name.

I want newfilepath=strcat(pathstr,'myfile').

Obviously it gives H:\user4\matlab\myfile what I don't want. How can I write my code.

Upvotes: 1

Views: 1127

Answers (2)

Gunther Struyf
Gunther Struyf

Reputation: 11168

Get the parent path manually:

islashes = strfind(pathstr,filesep());
newfilepath=fullfile(pathstr(1:islashes(end)),'..','myfile')

which uses also fullfile, filesep and strfind. Fullfile is really nice to concatenate strings while working with files and paths.

Or use '..' which Matlab will understand and thus will refer to the parent directory of the preceding directory:

newfilepath=fullfile(pathstr,'..','myfile')

Upvotes: 2

Nick
Nick

Reputation: 3193

I think you should use fileparts twice and then fullfile:

file = 'H:\user4\matlab\myfile.txt';
[pathstr, name, ext] = fileparts(file);
pathstr = fileparts(pathstr);
fullfile(pathstr, [name ext])

Upvotes: 4

Related Questions