如何在函数中修改数组?
MATLAB 是一种按值传递语言。我有一个处理像素邻居的递归函数。每次调用函数时复制图像(在我的例子中是两个图像)的成本非常高。
我使用全局变量来解决这个问题。还有其他方法可以使递归函数修改数组吗?
MATLAB is a pass by value language. I have a recursive function that processes pixel's neighbors. It is very expensive to make the copy of the image (in my case two images) each time the function is called.
I used global variables to solve the problem. Is there any other way to make a recursive function modify an array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里有三个选项,但也许您不需要其中任何一个,因为 Matlab 使用“写时复制”,即只有在修改变量时才会复制变量。
blockproc
或im2col
重写该函数。最后,如果您想保留当前的方案,我强烈建议使用 persistent< /a> 变量而不是全局变量。
You have three options here, but maybe you don't need any of them, since Matlab used 'copy-on-write', i.e. variables are only copied if you modify them.
blockproc
, orim2col
to rewrite the function.Finally, if you want to stay with your current scheme, I strongly suggest using persistent variables instead of globals.
MATLAB 并不总是按值传递,较新版本的 MATLAB 在某些情况下会按引用传递,请参阅 就地操作以及有关 MATLAB 内存管理的更一般性讨论 在这篇文章中。
如果没有 尾部调用优化,使用递归的效率就会很低,而且 MATLAB 也没有它据我所知,但每个递归都可以转换为循环。
MATLAB is not always pass-by-value, newer versions of MATLAB do pass-by-reference under some circumstances, see in-place operations and a more general discussion about MATLAB memory management in this SO post.
Without tail-call optimization it is inefficient to use recursion and MATLAB does not have it as far I know, but every recursion can be transformed into a loop.
如果您将递归函数设为另一个函数中的嵌套函数,其中存储图像数据,然后递归函数可以修改图像数据
If you make your recursive function a nested function within another function where the image data is stored, then the recursive function can modify the image data without needing to have it passed to it.
这是一个常见的误解。虽然MATLAB的sytanx是按值传递的,但它实际上并不像C中那样按值传递。解释器足够聪明,只在必要时才进行复制。因此,您应该继续按值传递,看看是否遇到内存问题。
正如其他发帖者所指出的,无论如何,您都应该尽量避免在 MATLAB 中使用递归。
This is a common misconception. Although the sytanx of MATLAB is pass by value, it does not actually pass by value as in C. The interpreter is smart enough to only make copies when necessary. So you should just go ahead and pass by value and see if you run into memory problems.
As other posters have noted, you should try to avoid recursion in MATLAB anyway.