Use an array element as a replacement in MATLAB regexpr

I have a line containing a math function like this:

sin(x[1]) + cos(x[2]) + tan(x[3]) + x[1]

Now I want to replace each x [number] with a letter of the alphabet using regexpr. The result should look like this:

sin(a) + cos(b) + tan(c) + a

So, I defined such an array of letters:

alphabet = ('a':'z')

This is my first regexpr that simply replaces every x [number] with "a":

regexprep(functionString,'x\[(\d+)\]','${alphabet(1)}');

What I tried replacing with the correct letter uses $ 1 instead of 1. I thought it would not use the alphabet (1), but a dynamically element in the right alphabetical index.

regexprep(functionString,'x\[(\d+)\]','${alphabet($1)}');

Instead, I get an error that the index is larger than the matrix.

Does anyone know what I'm doing wrong? How do I get the right letter? Thanks in advance!

+4
3

Matlab $1 . int32('1') = 49 Index exceeds matrix dimensions.

, str2num:

regexprep(functionString,'x\[(\d+)\]','${alphabet(str2num($1))}')
+3

, , , alphabet. :

regexprep(functionString,'x\[(\d+)\]','${char($1+48)}')

48 $1 char ASCII, 'a'.

+1

Have you tried regexprep(functionString,'x\[(\d+)\]','${alphabet($0)}');?

From what I see here: https://de.mathworks.com/help/matlab/ref/regexprep.html regex matches are based on 0, so the first should be $ 0.

0
source

Source: https://habr.com/ru/post/1663057/


All Articles