Copied cost function code from ex2.