Search this site
Embedded Files
Matlab by Examples
  • Tutorial
  • File operations
    • File commands
    • Files: read & write
      • fprintf
  • Matrix
    • cell array
      • Convert cell array
      • Single value to multiple fields
      • str2num
    • Check for subset
    • Create matrix
    • Index pairs permutations
    • Matrix to vector
    • Number range
    • Sort
      • Multiple columns
      • Reverse order of elements
    • triu elements
  • Multiprocessing
  • Plot
    • Axes
    • Bar plot
      • Barplot colors
      • Barplot percentage
    • Clustergram
      • to figure
    • Colors
      • Sample colors
    • Histogram
      • Histogram colors
      • Horizontal histogram
    • Remove top and right axes
    • Save as png
    • Subplot
    • Subtitle
  • Strings
    • Add prefix
    • Frequencies
    • Join
    • remove
  • Structure
  • System
    • Command line
      • Error
  • Time
Matlab by Examples

Strings

Matlab by Examples

Python | R

Replace substring

% replace all characters "a" with "x"

strrep('a1 a2 a3 a4', 'a', 'x')

   'x1 x2 x3 x4'

% replace file ending ".txt" with ".csv"

filename    = 'mydata.txt'

newFilename = strrep(filename, '.txt', '.csv')

  mydata.csv

% remove file ending '.txt'

filename = 'mydata.txt'

rawname  = strrep(filename, '.txt', '')

  mydata

% alternatively, use: 'erase'

rawname = erase(filename,'.txt')

  mydata

% using startswith and endswith to check presence of substring

filename = 'mydata.txt'

if endsWith(filename,'.txt'), filename = erase(filename,'.txt'), end

  mydata

Check / find substring

check for substring 'day'

~isempty(strfind('Friday','day'))

 1  % True: substring 'day' appears in string 'Friday'

get position of substring

strfind('Friday','day')

 4  % substring 'day' starts at character position 4 in string 'Friday'

Split a string

# separate words using the delimiter '_'

ID = strsplit('subjectA_sample02','_')

  {'subjectA'}    {'sample02'}

Result of strsplit is a cell array 

s1 = ID{1}

  'subjectA'

s2 = ID{2}

  'sample02'



Read more

→ Cell arrays: edit text in cell fields     replace, find, remove, ...


www.nlpca.org

Google Sites
Report abuse
Page details
Page updated
Google Sites
Report abuse