one index spans multiple functions

2 visualizzazioni (ultimi 30 giorni)
Tim
Tim il 22 Ott 2014
Modificato: Guillaume il 22 Ott 2014
function Myfun d=4; e=3; b=5;
fprintf('b=%d\n',b)
function a = A(x)
a = 0;
for b=1:10
a = a + d*e + b;
end
end
A(2)
fprintf('b=%d\n',b)
end
>> Myfun
b=5
ans = 175
b=10
I understand b is a local variable in the main function, but when it is put in the for loop of a nested function then it changed to a different value. How is it possible? Also, the output for the nested function is a and a=0 is its local variable. So a=a+d*e+b how did it come up with 175? which a in that equation is a variable and which one is the output? I know that b is an index variable spanning 2 functions, it is the local variable of the main function that is put in a nested function with a for loop. Can someone explain it to me?
  1 Commento
Image Analyst
Image Analyst il 22 Ott 2014
I'm having trouble understanding this. It looks like you have a function, some code, then a nested function in the middle of the code, then more code. Please attach your Myfun.m file with the paper clip icon. Then read this http://www.mathworks.com/matlabcentral/answers/13205-tutorial-how-to-format-your-question-with-markup and fix your formatting. Basically in the MATLAB editor, type control-a control-i, control-c, then come back here to Answers and type control-v to paste it the properly indented and formatted code. Next highlight the code you pasted in and click the {}Code icon above the text box.

Accedi per commentare.

Risposte (2)

Tim
Tim il 22 Ott 2014
function Mfun
d=4;
e=3;
b=5;
fprintf('b=%d\n',b)
function a = A(x)
a = 0;
for b=1:10
a = a + d*e + b;
end
end
A(2)
fprintf('b=%d\n',b)
end

Guillaume
Guillaume il 22 Ott 2014
Modificato: Guillaume il 22 Ott 2014
nested functions have access to the workspace of the containing function, so there is only ever one b variables for your two functions.
I must say I've never used nested functions and I don't see the need for them. For what you intended, I would use local functions which have their own workspace. That is rewrite your code as:
function Mfun
d=4;
e=3;
b=5;
fprintf('b=%d\n',b);
A(2, d, e)
fprintf('b=%d\n',b);
end
function a = A(x, d, e)
%A is a local function, it is only visible to Mfun.
a = 0;
for b=1:10
a = a + d*e + b;
end
end
In my opinion, it's clearer and it makes it obvious which variables are needed by the subfunction. The alternative is simply to rename your loop variable to a name that is not used by the containing function.

Community Treasure Hunt

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

Start Hunting!

Translated by