When is output assigned from function?

조회 수: 18 (최근 30일)
Max Frantz
Max Frantz 2021년 4월 21일
댓글: Max Frantz 2021년 4월 21일
I want to understand how functions output the output variable.
For instance, I have the function below.
function A = myfun(X)
len = length(X)
A = zeros(len,1); %preallocate
for ind = 1:len
A = X(1:ind) * X(ind:end) %some operation
end
end
In a script, I call B = myfun(Y)
Does B get updated in the script workspace every time something happens to A? Is there any issue with making multiple assignments to A, or is something like this better:
function A = myfun(X)
len = length(X);
temp_A = zeros(len,1); %preallocate
for ind = 1:len
temp_A = X(1:ind) * X(ind:end); %some operation
end
A = temp_A;
end
Thank you

답변 (1개)

Jan
Jan 2021년 4월 21일
편집: Jan 2021년 4월 21일
Your first version is fine. When the function myfun() exists, the contents of A is replied as first output. The value of B is not accessed and not even existing during the function runs.
The temporary variable does not have any benefit in the 2nd version.

카테고리

Help CenterFile Exchange에서 App Building에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by