Vector not recognised after while loop ends but still shows as output?
5 ビュー (過去 30 日間)
古いコメントを表示
Phoebe Tyson
2020 年 4 月 23 日
編集済み: Christian Andersen
2020 年 4 月 23 日
I have created a function
function [u,yhat] = power_method(M,y0,TOL)
uvec=zeros(1,100);
j=0;
y=y0;
y=M*y;
u=norm(y, inf);
yhat=y/u;
uvec(j+1)=u;
j=j+1;
y=M*yhat;
u=norm(y, inf);
yhat=y/u;
uvec(j+1)=u;
j=j+1;
U=abs(uvec(j)-uvec(j-1));
while U>TOL
y=M*yhat;
u=norm(y, inf);
yhat=y/u;
uvec(j+1)=u;
j=j+1;
U=abs(uvec(j)-uvec(j-1));
end
uvec=uvec(1:j)
end
I left the colon off the end of uvec so it would show me the output, which it does.
M=[-2 1 0 0; 1 -2 1 0; 0 1 -2 1; 0 0 1 -2];
y0=[1; 0; 0; 0];
TOL=10^-5;
[u,yhat] = power_method(M,y0,TOL)
It seems to work and I get results that look okay, however uvec is not in my workspace and when i try to call it after it displays:
Unrecognized function or variable 'uvec'.
Even though it displays it in the output of the above. Also j isnt stored.
I have put break points in and different places and the while loop is running as I'd expect and is storing the values at each iteration but once it exits the while loop it isnt stored. Why could this be?
0 件のコメント
採用された回答
Christian Andersen
2020 年 4 月 23 日
編集済み: Christian Andersen
2020 年 4 月 23 日
Variables in functions are only stored locally, and are deleted once the function returns.
If you want something in your workspace, you need to output it
As an example, if you want j in your workspace, you need to add it to your output argument list in your function definition:
function [u,yhat,j] = power_method(M,y0,TOL)
and then in your script (or command line):
M=[-2 1 0 0; 1 -2 1 0; 0 1 -2 1; 0 0 1 -2];
y0=[1; 0; 0; 0];
TOL=10^-5;
[u,yhat,j] = power_method(M,y0,TOL)
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!