copy from matlab demo.