MATLAB: How to take the cosine argument with regexp

regexp

I need to work with the arguments of the cosinus, I am working with a hughe matrix 10X10 with around 3 or 4 cosinus on each therm and I need to work only with the arguments.
I am trying to do with regexp.
A simplify example could be:
Take the arguments of the cosinus in the following expresion:
A=cos(-2/3*pi) - cos(phi*2 + pi/3);
What I did
str = 'cos(-2/3*pi) - cos(phi*2 + pi/3)';
expr = '[cos(\w)]';
[inputSignals]=regexp(str,expr)
The answer I have
inputSignals=[1 2 3 4 6 8 10 11 12 16 17 18 19 20 21 22 24 28 29 31 32]
What are the index from str to cos( 2 3 pi) and cos(phi 2 pi 3).
So I get the arguments without the symbols inside.
Here is my question:
¿ How can I write the expresion(expr) to have everything what is inside the brackets of the cosinus, write something instead of \w to have the full arguments?
PD: In the matrix I have more stuff with brackets, thats why I am asking Matlab to have cos(anything)

Best Answer

Perhaps I'm misunderstanding what you're looking for, but does the following match the pattern you want?
str = 'cos(-2/3*pi) - cos(phi*2 + pi/3)';
exp = '(?<=cos\()[0-9a-z\/\*\-\s\+]*(?=\))';
inputSignals = regexp(str, exp, 'match')
returns
inputSignals =
1×2 cell array
'-2/3*pi' 'phi*2 + pi/3'
This regex translates to "look for any group of letters, numbers, underscores, or +-*/ preceded by cos( and followed by ).
As Walter points out, it won't work if any of your cosine terms include parentheses themselves, i.e
str2 = 'cos(-2/3*pi) - cos((x+1)/2) + cos(phi*2 + pi/3)';
regexp(str2, expr, 'match')
returns (not what you want):
ans =
cell
'-2/3*pi) - cos((x+1)/2) + cos(phi*2 + pi/3'
Related Question