arupnathdaw
arupnathdaw

Reputation: 293

How to substring of a string in matlab array

I have a matlab cell array of size 20x1 elements. And all the elements are string like 'a12345.567'.
I want to substitute part of the string (start to 9th index) of all the cells. so that the element in matrix will be like 'a12345.3'.
How can I do that?

Upvotes: 0

Views: 122

Answers (2)

rayryeng
rayryeng

Reputation: 104464

Another method that you can use is regexprep. Use regular expressions and find the positions of those numbers that appear after the . character, and replace them with whatever you wish. In this case:

M = { 'a12345.567'; 'b12345.567' }; %// you have 20 entries like these - Taken from Shai
MM = regexprep(M, '\d+$', '3');

MM = 

    'a12345.3'
    'b12345.3'

Regular expressions is a framework that finds substrings within a larger string that match a particular pattern. In our case, \d is the regular expression for a single digit (0-9). The + character means that we want to find at least one or more digits chained together. Finally the $ character means that this pattern should appear at the end of the string. In other words, we want to find a pattern in each string such that there is a number that appears at the end of the string. regexprep will find these patterns if they exist, and replace them with whatever string you want. In this case, we chose 3 as per your example.

Upvotes: 0

Shai
Shai

Reputation: 114786

You can use cellfun:

M = { 'a12345.567'; 'b12345.567' }; %// you have 20 entries like these
MM = cellfun( @(x) [x(1:7),'3'], M, 'uni', 0 )

Resulting with

ans =
  a12345.3
  b12345.3

For a more advanced string replacement functionality in Matlab, you might want to explore strrep, and regexprep.

Upvotes: 3

Related Questions