필터 지우기
필터 지우기

Output argument's name same as input argument's

조회 수: 21 (최근 30일)
Matvii Kistaiev
Matvii Kistaiev 2022년 4월 27일
댓글: Walter Roberson 2022년 4월 27일
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