Output argument's name same as input argument's

37 次查看(过去 30 天)
Is there any differences in MATLAB behavior in these cases:
function output = func(input)
output = do_smth(input, ... );
end
And
function input = func(input)
input = do_smth(input, ... );
end
By function
do_smth(input, ... )
I mean a general abstraction, just something, not necessarily passing input as an arguments to some function.

回答(2 个)

Chunru
Chunru 2022-4-27
Functionally, they are same.
However, some differences may exist:
  • The obvious one is the program style (using input as output may not be a good style)
  • Memory allocation: If input is an array and it is not changed within function, MATLAB may not allocate input locally. If there is a statement input=do_something insede the function, it means input has changed inside the function and a local copy of input need to be allocated.

Walter Roberson
Walter Roberson 2022-4-27
Yes there is.
In the case where you have a function that has the same name for input and output, and part of the input is modified, and the function is being called within another function, and that calling function uses the same names for input and output... if all of these are true, then the variable being passed in can be eligible for in-place modification instead of copy-on-write.
It is a difficult set of circumstances to get right, and there is no guidelines from Mathworks about how to code to recognize the situation in mex code in order to be able to increase efficiency by avoiding a data copy.
  2 个评论
Matvii Kistaiev
Matvii Kistaiev 2022-4-27
Thank you for your answer! And maybe there is a way to test on some particular function whether it passes an argument "by reference" or "by value"?
Walter Roberson
Walter Roberson 2022-4-27
Every argument is passed "by reference" in MATLAB (at least for the purposes of .m and .p and .mex*) .
The reference might be to a handle object, in which case changes to the properties are reflected immediately for everywhere that has a copy of the same handle.
The reference might be (more commonly is) to a value object (which includes the base arithmetic classes). In this case, copy-on-write semantics apply -- with the modification that when the reference count is 1 and somehow some other information is conveyed (through undocumented means), then sometimes an array can be modified in-place instead of creating a new array. There is no publically known way of detecting when that is happening.
There is no method available at the MATLAB level of testing the reference count to an input parameter. There are some methods available at the mex level, but those have become increasingly unreliable.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by