Strrep MATLABs function with overlapping search results

MATLABs strrep does things differently than I expected:

 strrep('ababab', 'bab', 'bbb') 

I hope that the strings will be replaced in stages, thus, first abbbab and than abbbbb . However, MATLAB returns abbbbbb (note the extra, 6th b at the end).

What does MATLAB do under the hood? Looking for indexes and then inserting a new row into each index? Is something completely different?

And, most importantly, how can I archive the intended result?


To be precise, the above example is just a minimal example of reducing additional sources of error. In the real world, I would like to replace sequences in integer vectors:

 strrep([1 0 1 0 1 0], [0 1 0], [0 0 0]) 

and get

 1 0 0 0 0 0 
+4
source share
1 answer

Matlab documentation for strrep tells you what you need to know. In the "Tips" section at the bottom of the page:

Before replacing strings, strrep finds all instances of oldSubstr in origStr, like the strfind function. For overlapping patterns, strrep performs multiple replacements. See the last example in the Examples section.

The final example compares the behavior of strrep and regexprep . I think regexprep will do what you want in a string. To work with numbers, you can convert them to a string using char(vector) , run regexprep , and then convert back to numbers using double(string) .

+2
source

All Articles