Problem 221. Boolean algebra

Your contractor from Elbonia has sent you the prototype of the new logical unit. It turns out that the only logical relation it understands is "nand":

nand(a,b) := ~(a&b)

Your team has been developing code using the usual logical operators following MATLAB syntax: ~,& and |. To save the project you need to write a translator that expresses MATLAB logical expressions using only the nand function.


  • expr: a string containing a valid logical expression in MATLAB, that relates the two logical variables a and b


  • out: a string containing an equivalent logical expression that may only use the function nand(a,b).

Example 1:

    expr = 'a|(~b)'
  =>out  = 'nand(nand(a,a),b)'

Example 2:

    expr = '(a & ~a) | ~(a|b)'
  =>out  = 'nand(nand(nand(a,a),nand(b,b)),nand(nand(a,a),nand(b,b)))'


It is not necessary to provide the shortest solution. A solution always exists. The input string is non-empty and always evaluates to true or false, if a and b are logical variables. All substrings in the output that are not 'a','b','0','1','true','false','(',')' or'nand' will be ignored.

Solution Stats

20.97% Correct | 79.03% Incorrect
Last solution submitted on Dec 11, 2015

Solution Comments

Discover MakerZone

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

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!

Join the 15-year community celebration.

Play games and win prizes!

Learn more