如何在函数中修改数组? [英] How to modify an array in function?

查看:536
本文介绍了如何在函数中修改数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

  1. @gnovice 所述,您可以使用嵌套函数.嵌套函数内部使用的变量在嵌套函数和封闭函数之间共享.嵌套函数在调试时有些棘手,而编写/理解起来则更为复杂.
  2. 您可以将图像存储为处理对象的属性,通过引用传递.
  3. 为了不使用递归函数,可以编写不同的代码,因为Matlab并不是使用递归函数的最佳语言.如果您有权使用图像处理工具箱,则可以使用 im2col 重写功能.
  1. 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.
  2. You can store your images as properties of a handle object, which is passed by reference.
  3. 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, or im2col to rewrite the function.

最后,如果您希望保留当前的方案,我强烈建议您使用永久变量而不是全局变量.

Finally, if you want to stay with your current scheme, I strongly suggest using persistent variables instead of globals.

这篇关于如何在函数中修改数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆