MATLAB中非负平方的简短历史
In my first year at MathWorks (1987!), a professor I know got in touch with me. He was trying to solve a least squares problem with nonnegativity constraints. Having been raised properly, I knew immediately where to get a great algorithm
- Lawson and Hanson, "Solving Least Squares Problems", Prentice-Hall, 1974, Chapter 23, p. 161.
Contents
fortran代码
The Fortran code is supplied in the book and the professor I spoke with did a fairly faithful translation, despite MATLAB not yet having agoto陈述。问题是,它无法正常工作。他要我看看。我记得很兴奋,因为我爱nnls如L-H致电算法。但是,倾倒别人翻译的Fortran很快就会失去其Pizzazz。
Let me give you some statistics on the Fortran code itself.
- 总计326行
- 〜150行评论
- 留下〜175行可执行的代码
- 主双环,〜125行可执行的代码(行83-289)
尤里卡的时刻
拖延有时会回报。我没有读取M文件代码,而是将其与Fortran逐线比较,而是打开了该算法的参考。这是我发现的东西。
Do you see what I see? I see the problem being talked about in terms of matrices and vectors. Hmmm, maybe I can implement it straight from the algorithm description, bypassing the Fortran implementation. And so I did.
MATLAB代码
MATLABshipped with the functionnnls, which ultimately was renamed tolsqnonneg并已更新以包含一些代码,以使用我们的其他优化例程进行标准化。我在不到半天的时间内编写和运行了代码,包括在教授发送给我的示例中正确地工作,这些示例没有用他的翻译代码工作。
对于M文件,代码统计信息看起来像这样。
- 206 lines total
- ~80 blank and comment lines
- 〜125行可执行的代码,其中〜55处理我们其他优化例程共有的基础架构
- 主迭代环(嵌套时环)的〜50行
得到教训
- I relearned from this experience that it is worth going back and thinking about code and the algorithm before diving in. I guess I had to learn this one a few times in the course of my progamming life! While the Fortran and both versions of the M-files were based on the same algorithm, I was able to bypass the code written and write a version using the matrix notation of the reference.
- The MATLAB code is shorter, though I am sure some will say that it is not那么多shorter.
- The algorithm, when I wrote it, really sunk in for me, since instead of being mired in loops, I watched variables move in and out of the active set. It was very interesting to see the algorithm work from a less nitty-gritty level, yet still capturingallthe details.
要分享您的任何经验,即对算法的思考与假装方式不同的方式有所不同?添加您的想法这里.