Code is basically done, minor problem
이전 댓글 표시
Hi, I have this script almost completely figured out (the specifics at least) but I can't get it to run. The error message is saying that the function can't be defined in this context. I believe it's because the function isn't supposed to be inside the script, but I'm not sure on exactly how to fix it. Do I just copy and paste the functions into a new script and save them as their own m-file? And if so what do I replace the function with in my real script?
Here's the script:
%%Part 1
clc;
clear all;
function [v,lambda]=powermat1([6 5;1 2],[0 1]',10) %%define matrix, vector, and loop
v =[0 1]' ;
A=[6 5;1 2];
for n = 1:10 %%setting the process for 1 to 10
vnew = A*v;
lambda = norm(vnew,inf)/norm(v,inf);
fprintf('n = %4d, lambda = %g, v =[ %g %g ] \n', n, lambda, v');
v=vnew;
end
v = v/norm(v); %normalise x
fprintf('n = %4d ,normalised v = [%g %g ]\n', n, v')
%%Part 2
clc;
clear all;
A=[6 5;1 2];
[eigen_vector, eigen_value]=eig(A) %%checking answer
답변 (3개)
Image Analyst
2015년 11월 7일
Get rid of the script before of the function declaration. The script just does clear all, but it's still a script, and you can't have a script and function(s) all in the same m-file. Or else put
function myfunction
as the first line. Use whatever the m-filename is.
Star Strider
2015년 11월 7일
‘Do I just copy and paste the functions into a new script and save them as their own m-file?’
Yes! Spot on!
‘And if so what do I replace the function with in my real script?’
Call it just as you would any other external function:
[v,lambda]=powermat1([6 5;1 2],[0 1]',10)
You’ll probably have to experiment with them to get everything to work correctly, but that’s just part of the ongoing process of becoming a more skilled programmer. If you have problems you have trouble solving, describe your problem, post your code and any error messages, and you will get help here.
Walter Roberson
2015년 11월 7일
0 개 추천
Remove the clc and clear all and save the resulting function in powermat1.m
댓글 수: 1
Walter Roberson
2015년 11월 7일
function [v,lambda] = powermat1(A,v,maxn) %%define matrix, vector, and loop
for n = 1:maxn %%setting the process for 1 to 10
vnew = A*v;
lambda = norm(vnew,inf)/norm(v,inf);
fprintf('n = %4d, lambda = %g, v =[ %g %g ] \n', n, lambda, v');
v = vnew;
end
카테고리
도움말 센터 및 File Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!