0

In Matlab I have a string, that represents a function. Let it be something like that '...sin(arcsin(f_2))...'. I want to find all appearances of 'sin(arcsin(F))' for any F and replace it with simple 'F'.

I don't know what kind of function if F. It may be 'exp' or 'cos' or something else.

How can I do it? Is it any smart way to do it without while-loop?

Macaronnos
  • 647
  • 5
  • 14

1 Answers1

2

There's a couple of ways:

>> char(sym(str))  %// requires symbolic toolbox

>> regexprep(str, 'sin\(arcsin\(F\)\)', 'F')

>> strrep(str, 'sin(arcsin(F))', 'F')

The nice thing about the regexprep method is that you can be a lot more flexible with regard to spacing and casing:

>> regexprep(str, 'sin\s*\(\s*a(rc)*sin\s*\(\s*F\s*\)\s*\)', 'F', 'ignorecase')

the call above will convert all of the following:

>> str = ' sin (    arcsin(F )  )'
>> str = 'sin(arCSin(f) )'
>> str = '   Sin             (arcsin(f)  )       )'
>> str = 'Sin(Asin(f)))'

etc.

Note that for both methods above: str may be either a string or cell array of strings.

EDIT

You have indicated that F may be anything. That complicates matters. For simple matches you could still use something like

>> regexprep(str, 'sin\s*\(\s*a(rc)*sin\s*\(\s*(.+)\s*\)\s*\)', '$2', 'ignorecase')

But you'll have to be careful, because things like

>> str = 'acos(log( sin(arcsin( exp(x) )) * sin(x) ))'

will be incorrectly converted :

>> regexprep(str, 'sin\s*\(\s*a(rc)*sin\s*\(\s*(.+)\s*\)\s*\)', '$2', 'ignorecase')
ans = 
    acos(log( exp(x) )) * sin(x)

(note the incorrect bracketing). One solution is to use lazy operators:

>> regexprep(str, 'sin\s*\(\s*a(rc)*sin\s*\(\s*(.+?)\s*\)\s*\)', '$2', 'ignorecase')

but beware that you're really crossing over the border of what regular expressions can (or should) be used for. Not all possible cases will be handled successfully this way...See also this legendary answer

The best way by far is to prevent these strings from being generated that way in the fist place. I suspect that a simple sym/simplify will do away with this whole problem.

Community
  • 1
  • 1
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96