通过引用传递的 MATLAB 函数

标签 matlab memory memory-management pass-by-reference

我有一个包含属性的类(假设类文件的名称是 inputvar),

我将它用作两个不同函数的输入参数,这两个函数的计算完全相同,但代码略有不同,稍后我将对此进行解释。

对于第一个函数(假设名称是 myfun1),我这样写输入参数:

f = myfun1 (inputvar)

所以每次我想在函数内部使用类中的变量时,我都必须调用 inputvar.var1inputvar.var2

对于第二个函数 (myfun2),我在输入参数中写入了类中的每个变量,所以它看起来像这样:

f = myfun2 (inputvar.var1, inputvar.var2, ...等)

在函数内部,我只需使用 var1var2 等,而无需包含类名。

运行两个函数后,我发现myfun2运行速度比myfun1快很多,大约60%(我用的是tic-toc)。

谁能给我解释一下这是为什么?

最佳答案

reference :

MATLAB uses a system commonly called "copy-on-write" to avoid making a copy of the input argument inside the function workspace until or unless you modify the input argument. If you do not modify the input argument, MATLAB will avoid making a copy. For instance, in this code:

function y = functionOfLargeMatrix(x) y = x(1); MATLAB will not make a copy of the input in the workspace of functionOfLargeMatrix, as x is not being changed in that function. If on the other hand, you called this function:

function y = functionOfLargeMatrix2(x) x(2) = 2; y = x(1); then x is being modified inside the workspace of functionOfLargeMatrix2, and so a copy must be made.

根据上面的说法,当您直接传递一个类对象并更改该对象的任何成员时,将应用该类的整个复制操作。

另一方面,通过将类成员作为单独的参数,复制操作仅适用于函数中修改的相关成员,从而加快执行速度。

关于通过引用传递的 MATLAB 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17932396/

相关文章:

image-processing - 带有自定义插值内核的 MATLAB imresize

c - 需要帮助将 MATLAB 代码转换为 C

c - 在共享内存中分配 N 大小的数组

java - 哪种设计消耗更少的内存?

android - 加载 390k md2 模型时内存不足

c++ - 使用 vector 时出现奇怪的运行时错误

c - 尽管释放结构内存泄漏

arrays - 具有数组输入的 Matlab 匿名函数

matlab - 打破嵌套循环

c++ - Pimpl 成语内存使用