Code is basically done, minor problem
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Antworten (3)
Image Analyst
am 7 Nov. 2015
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.
0 Kommentare
Star Strider
am 7 Nov. 2015
‘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.
0 Kommentare
Walter Roberson
am 7 Nov. 2015
Remove the clc and clear all and save the resulting function in powermat1.m
1 Kommentar
Walter Roberson
am 7 Nov. 2015
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
Siehe auch
Kategorien
Mehr zu Numerical Integration and Differentiation finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!