Unassigned variables and accessing them from outside the function
이전 댓글 표시
I have this code:
function [zr,w,R,q,mat] = test(z)
lambda = 1;
w0 = 1;
zr = (pi*w0^2)/lambda;
w = w0*sqrt(1+(z/zr)^2);
R = z + zr^2/z;
q = z + 1i*zr;
mat = [1 z; 0 1];
end
but I not want to have to assign lambda and w0 ( or even z for that matter ), i want them to just stay variables UNLESS I assign them ... This is because often it's easier to interpret one variable in terms of the other instead of just having some number... so inputting
[zr,w,R,q,mat] = test(z)
should return the variables exactly how they look inside the function:
zr =
(pi*w0^2)/lambda
w =
w0*sqrt(1+(z/zr)^2)
R =
z + zr^2/z
q =
z + 1i*zr
mat =
1 z
0 1
also, how come these don't exist outside of the function? I can't call q anymore for example after executing test because it doesn't appear to exist anymore.
EDIT:
assigning them as global worked as far as keeping the values assigned by the function :] yay! i don't know if that's the proper way, but it worked XD ... still not sure how to return unassigned variable tho ...
댓글 수: 2
Image Analyst
2015년 5월 17일
That's only okay (making them global) if you don't accept them as input arguments, or return them as output arguments. Otherwise an error will say something like "zr might be used incompatibly or redefined?
If values are not assigned, then they don't even exist and you can't return them. If you have arguments in the output arg list, and you did not assign them, then when you call the function it will say something like "Output argument "q" (and maybe others) not assigned during call"
Solarmew
2015년 5월 17일
채택된 답변
추가 답변 (1개)
Image Analyst
2015년 5월 17일
They DO exist outside the function. When, in the main (calling) function, you do this:
[zr,w,R,q,mat] = test(z)
that means that zr, w, R, q, and mat will have the same values in your calling function that they had inside the test() function (because you used the same names for them).
I do not understand your desire not to pass in any "z" value to test(). What's the point of having input variables then? If you want z to be a constant, just assign it inside test.
I do not understand the need to avoid assigning lambda and w0 inside the function. What's the big deal? What's wrong with doing that? Just how do you expect them to have a value if you don't assign one???
카테고리
도움말 센터 및 File Exchange에서 Common Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!