Eren Golge
Eren Golge

Reputation: 790

how to replace a portion of a string in matlab

I have a string matrix filled with data like

matrix = ['1231231.jpeg','4343.jpeg',...]

and I want to remove its file extension and get

matrix  = ['1231231', '4343']

How can I do it? is there any function or what :)

Upvotes: 1

Views: 2024

Answers (5)

gevang
gevang

Reputation: 5014

Note: A matrix from (vertical) concatenation of strings with different lengths will not work (except for the special case of equal-length strings). Each char is treated as a single matrix element by vertcat when calling[A;B].

Alternative, using cell array and cellfun (+independent of file extensions):

matrix = {'1231231.jpeg','4343.jpeg'};
matrix_name = cellfun(@(x) x(1:find(x == '.', 1, 'last')-1), matrix, 'UniformOutput', false);

Upvotes: 1

user1595178
user1595178

Reputation: 181

Assuming the matrix looks like

 matrix = ['1231231.jpeg';
           '4343.jpeg';
            ....];

(; instead of ,). If ',' is used, the chars in the matrix are concatinated automatically.

You can use arrayfun to perform an operation on each index of a matrix. The following command should work

arrayfun(@(x) matrix(x,1:strfind(a(matrix,:),'.jpeg')-1), str2num(matrix(:,1))', 'UniformOutput' , false)

Upvotes: 1

user1401864
user1401864

Reputation:

You could always loop through them and parse them like:

r[i] = regexp(char(string), '(?<dec>\d*).(?<ext>\w*)', 'names');

use r[i].dec for the number value.

Upvotes: 1

slayton
slayton

Reputation: 20319

User fileparts, it returns three variables the path, name, and extension of the file. So this should work for you

[~, fName, ext] = fileparts(fileName)

Upvotes: 3

Gir
Gir

Reputation: 849

there is a function for this in matlab

http://www.mathworks.com/help/techdoc/ref/fileparts.html

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

pathstr =
H:\user4\matlab

name =
classpath

ext =
.txt

Upvotes: 1

Related Questions