23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3 Basic Program Components<br />

The dynamic expression reverses the order of the letters that make up the<br />

string, and then attempts to match as much of the reversed-order string as<br />

possible. This requires a dynamic expression because the value for $1 relies<br />

on the value of the token (.{3,}):<br />

% Put the string in lowercase.<br />

str = lower(...<br />

'Find the palindrome Never Odd or Even in this string');<br />

% Remove all nonword characters.<br />

str = regexprep(str, '\W*', '')<br />

str =<br />

findthepalindromeneveroddoreveninthisstring<br />

% Now locate the palindrome within the string.<br />

palstr = regexp(str, '(.{3,}).?(??@fliplr($1))', 'match')<br />

str =<br />

'neveroddoreven'<br />

Dynamic expressions in <strong>MATLAB</strong> have access to the currently active<br />

workspace. This means that you can change any of the functions or variables<br />

used in a dynamic expression just by changing variables in the workspace.<br />

Repeat the last command of the example above, but this time define the<br />

function to be called within the expression using a function handle stored in<br />

the base workspace:<br />

fun = @fliplr;<br />

palstr = regexp(str, '(.{3,}).?(??@fun($1))', 'match')<br />

palstr =<br />

'neveroddoreven'<br />

Dynamic Commands that Serve a Functional Purpose — (?@cmd). The<br />

(?@cmd) operator specifies a <strong>MATLAB</strong> command that regexp or regexprep<br />

is to run while parsing the overall match expression. Unlike the other<br />

dynamic expressions in <strong>MATLAB</strong>, this operator does not alter the contents<br />

of the expression it is used in. Instead, you can use this functionality to get<br />

<strong>MATLAB</strong>toreportjustwhatstepsit’stakingasitparsesthecontentsofone<br />

of your regular expressions.<br />

3-62

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!