Solution in GNU Octave, probably works in MATLAB too but haven't tested in MATLAB