Notes on Homework 1

In [1]:
format compact

The last question asks you to use boolean_print_TT_fn.m (available on canvas) to print the truth table. Please read this additional note if you have trouble using this function.

Function as an input variable

Typically you pass data (e.g. scalars, arrays…) to a function. But the function boolean_print_TT_fn() accepts another function as the input variable.

Inline function as an input variable

Let’s make two inline functions:

In [2]:
func1 = @(a) a;
func2 = @(a,b) a&b;

boolean_print_TT_fn(func,1) prints the truth table for a function with a single input:

In [3]:
boolean_print_TT_fn(func1,1)
_____
a|out
0|0
1|1

boolean_print_TT_fn(func,2) prints the truth table for a function with two inputs:

In [4]:
boolean_print_TT_fn(func2,2)
_______
a|b|out
0|0| 0
0|1| 0
1|0| 0
1|1| 1

Standard function as an input variable

However, if you try to pass a standard function (i.e. defined in a separate file) to boolean_print_TT_fn(), it will throw you some weird error:

In [5]:
%%file func2_fn.m
function s=func2_fn(a,b)
    s = a&b;
end
Created file '/Users/zhuangjw/Research/Computing/personal_web/AM111/docs/func2_fn.m'.
In [6]:
boolean_print_TT_fn(func2_fn,2)
Not enough input arguments.
Error in func2_fn (line 2)
    s = a&b;

To fix this error, you can put @ in front of your function, as suggested here.

In [7]:
boolean_print_TT_fn(@func2_fn,2)
_______
a|b|out
0|0| 0
0|1| 0
1|0| 0
1|1| 1

(That’s MATLAB-specific design. Other languages like Python treat inline and standard functions in the same way.)