Matlab函数参数传引用方法

Can MATLAB pass by reference?

If you are attempting to use pass-by-reference to modify the input argument passed into a function, the answer to the question depends on whether the input is a handle object or a value object. The two types of objects are described in the Object-Oriented Programming (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_oop/brfylq3.html) and Programming Fundamentals (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/brtm8si.html) sections of the documentation. By default, objects (including matrices, arrays, etc. of the built-in data types) are value objects.

Handle objects do exhibit reference behavior when passed as function arguments; value objects do not. When you pass a handle object to a function, MATLAB still copies the value of the argument to the parameter variable in the function (with one bit of subtlety; see below.) However, all copies of a handle object refer to the same underlying object.

If a function modifies a handle object passed as an input argument, the modification affects the object referenced by both the original and copied handles. In this case, the function does not need to return the result to be reassigned.

If instead you are attempting to use pass-by-reference to avoid unnecessary copying of data into the workspace of the function you're calling, you should be aware that 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.

For more information on this behavior, read this posting (http://blogs.mathworks.com/loren/2006/05/10/memory-management-for-functions-and-variables/) on Loren Shure's blog.

 

from: http://matlab.wikia.com/wiki/FAQ#Can_MATLAB_pass_by_reference.3F

转载于:https://www.cnblogs.com/nn0p/archive/2013/01/16/2862159.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值