Could anyone can help me with a question about function workspace?

I came to a question with following code:
Function [x,y] = myworkspace(a,b)
x = a + b;
y = x * b;
z = a + b;
end
Example Q1: What will the value of a,b,x,y and z be after the following code is run?
Example A1 is as follows:
>>clear all
>>a = 2;
>>b = 3;
>>z = 1;
>>[y,x] = myworkspace(b,a)
y = 5
x = 10
*>>z
z = 1*
Example Q2: What will the value of a,b,x,y and z be after the following code is run?
Example A2 is as follows as well:
>>x = 5;
>>y = 3;
>>[b,a] = myworkspace(x,y)
b = 8
a = 24
*>>z
??? Undefined function or variable 'z'.*
I am wondering why the values of z above are like that (in Bold)? I am confusing since z = a + b and both elements are defined...
Could you please tell me why it is the case?

1 件のコメント

Henry Mao
Henry Mao 2015 年 9 月 19 日
Sorry for my mistyping, it's not in bold but between asterisks...

サインインしてコメントする。

 採用された回答

dpb
dpb 2015 年 9 月 19 日

0 投票

The definitions in the function are local and the dummy arguments are assigned values by position, NOT by association of name with that of the calling workspace variable--they don't have to agree whatsoever--you can call myworkspace(z,pi) just as well and internally to the function you'd have (first case) a=1,b=3.141...
Also arguments are passed but cannot be modified; they're essentially passed by value albeit that may not be the actual passing mechanism it's what it appears to be.
Hence, in the first case the value of z is that previously defined; in the second z hasn't been defined as whatever it is internal to the function workspace is temporary and exists only in that scope; when the function returns, whatever it was therein is lost irretrievably since you only return the result of x and y.

1 件のコメント

Henry Mao
Henry Mao 2015 年 9 月 19 日
Thank you so much for your patience and clear answer! I finally got it! Thank you again!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Entering Commands についてさらに検索

質問済み:

2015 年 9 月 19 日

コメント済み:

2015 年 9 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by