Home > Software design >  Systematically remove strings from a cell
Systematically remove strings from a cell

Time:09-10

I have a cell name1 (nx1)

a.mat
b.mat
c.mat
...
z.mat

I'd like to create a cell name2 in which all the .mat have been removed so I'll have this

a
b
c
...
z

I could create a loop and remove the .mat with strsplit or fileparts but this would be very cumbersome. Anyone has a shortcut how to do this? Thanks in advance!

CodePudding user response:

You can use erase since R2016b

name1New = erase( name1, '.mat' );

Or strrep since forever

name1New = strrep( name1, '.mat', '' );

Both of these will remove all instances of .mat within the cell, which is usually fine for file names and their extensions, but if for some reason you need to strictly confine this to .mat at the end of the strings, you can use regexprep

name1New = regexprep( name1, '\.mat$', '' );

Example:

name = {'blah.mat', 'foo.mat', 'bar.matTest.mat'};
erase(name,'.mat')
ans =
  1×3 cell array
    {'blah'}    {'foo'}    {'barTest'}
regexprep( name, '\.mat$', '' )
ans =
  1×3 cell array
    {'blah'}    {'foo'}    {'bar.matTest'}
  • Related