如何在函数中修改数组? [英] How to modify an array in function?
问题描述
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?
推荐答案
您在这里有三个选项,但是也许您不需要其中的任何一个,因为Matlab使用了写时复制"功能,即仅复制变量如果您修改它们.
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.
- 如 @gnovice 所述,您可以使用嵌套函数.嵌套函数内部使用的变量在嵌套函数和封闭函数之间共享.嵌套函数在调试时有些棘手,而编写/理解起来则更为复杂.
- 您可以将图像存储为处理对象的属性,通过引用传递.
- 为了不使用递归函数,可以编写不同的代码,因为Matlab并不是使用递归函数的最佳语言.如果您有权使用图像处理工具箱,则可以使用
im2col
重写功能.
- As @gnovice mentions, you can use a nested function. Variables used inside the nested function are shared between the nested function and the enclosing function. Nested functions are somewhat tricky to debug, and a bit more complicated to write/understand.
- You can store your images as properties of a handle object, which is passed by reference.
- You can write code differently in order to not use a recursive function, since Matlab isn't the best language for using those. If you have access to the image processing toolbox, you may be able to use functions like
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.
这篇关于如何在函数中修改数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!