Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a file name string in MATLAB?

Tags:

string

matlab

I would like to have the original string 'black.txt' to be parsed into a = 'black' and ext = '.txt'. Every filename/string is going to have the extension '.txt'. I'm wondering what would be the easiest way of achieving this in MATLAB so that I can concatenate the new string appropriately?

like image 952
stanigator Avatar asked Dec 13 '22 03:12

stanigator


1 Answers

I would suggest using the FILEPARTS function to parse a file name string. Here's an example:

>> fileString = '\home\matlab\black.txt';
>> [filePath,fileName,fileExtension] = fileparts(fileString)

filePath =
   \home\matlab

fileName =
   black

fileExtension =
   .txt

You can then put the file string back together with simple string concatenation (for just the file name) or using the FULLFILE function (for an absolute or partial file path):

fileString = [fileName fileExtension];  %# Just the file name
fileString = fullfile(filePath,[fileName fileExtension]);  %# A file path

Using FULLFILE is easier and more robust with respect to running your code on different operating systems, since it will choose the appropriate file separator for you ("\" for Windows or "/" for UNIX).

like image 100
gnovice Avatar answered Dec 22 '22 01:12

gnovice