Michael Fejtek
Michael Fejtek

Reputation: 1

Matlab - Using part of a filename from an existing file to name a new file

I have the following problem in Matlab. I'm opening an existing file with this line:

fileID = fopen(filename,'r');

I then create a new file with this line:

fid=fopen('output.txt','w');

That works just fine. The problem is, I don't want it to be called "output". I would like to call it using the original filename and adding a bit of string to it, like this: "filename_new.txt". The output file also has to be a .txt file, regardless of what the original one was. I know I can get the name of the original file into string using this:

[pathstr, name, ext] = fileparts(filename) 

but I have no idea where to go from there. So to sum it up, the new file should be called "name_new.txt". I have a feeling this is either trivial to you guys or you're gonna tell me it's not actually possible this way. Either way, I'd be grateful for any help.

Upvotes: 0

Views: 3018

Answers (3)

Yuzu
Yuzu

Reputation: 1

%% Rename whole *copy.png -> .png  by JYJ

root_dir = '/Users/Yoojeong/Desktop/stims/png';

%retrieve the name of the files only
listdir = dir(fullfile(root_dir, '*.png'));

% i = 1; 
    for i = 1:length(listdir)
[pathname, filename, extention] = fileparts(listdir(i).name);

%the new name 
newFilename = [filename(1:end-5),'.png'];
movefile(fullfile(root_dir, listdir(i).name), fullfile(root_dir,newFilename))
    end

Upvotes: 0

tkroman
tkroman

Reputation: 4798

http://www.mathworks.com/help/matlab/ref/fullfile.html

Try then

f = fullfile(pathstr, strcat(name,'_new.',ext))

Upvotes: 1

Schorsch
Schorsch

Reputation: 7905

You can try this:

filename_out = [filename(1:end-4),'_new.txt'];  
fid=fopen(filename_out,'w');

filename(1:end-4) is a quick and easy way to remove the .txt ending. If you know that it'll all be txt-files, this should suffice.
With the [] you can combine the two strings, in this case appending a _new.txt

Upvotes: 1

Related Questions