MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply TodayOne of the most indispensable things about a great text editor for programming is the ability to quickly jump between matching parentheses. If you have a line like,

if (f(a) >= b(c, d(e*(f-g))))

it very convenient to place your cursor at, say, the second to last closing parenthesis, and have the editor show you where is the matching opening parenthesis. (In this example, it is the one just after `b`.)

For this problem, you should write a function that takes a string `s` like `'if (f(a) >= b(c, d(e*f(-g))))'` and an integer `n` representing a character position within the string. Your function should return the index of the matching parenthesis.

For example:

>> s = 'if (f(a) >= b(c, d(e*f(-g))))';

>> find_matching_paren(s, 4)

ans =

29

>> find_matching_paren(s, 6)

ans =

8

>> find_matching_paren(s, 27)

ans =

19

You can assume that `n` will always be the position of either an open or closing parenthesis.

You can assume the string will always have balanced parentheses.

96 correct solutions
101 incorrect solutions

Last solution submitted on Jul 10, 2014

4 players like this problem

1 Comment

Aurelien Queffurust
on 29 Nov 2012

wow I don't find the words to comment this solution except who can read that?!!

2 Comments

Jean-Marie SAINTHILLIER
on 29 Apr 2014

Wonderful solution.
Technically, I don't understand where ans is created. If I break this code, I obtain an error (ans is undefined). It seems that the line 4 create ans but only in the function (?).

Khaled Hamed
on 30 Apr 2014

Hi Jean-Marie. I haven't bee around for some time now. Well, that turned out to be a bug...
http://www.mathworks.com/matlabcentral/answers/46972-is-this-a-possible-matlab-bug-further-strange-behavior

2 players like this solution

1 Comment

Jean-Marie SAINTHILLIER
on 5 Jul 2013

Brilliant !!!

1 Comment

Patrick Kalita
on 26 Jan 2012

vectors, schmectors!

1 Comment