0

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.