Code is basically done, minor problem

4 ビュー (過去 30 日間)
Dylan Myers
Dylan Myers 2015 年 11 月 7 日
コメント済み: Walter Roberson 2015 年 11 月 7 日
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
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
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
Walter Roberson 2015 年 11 月 7 日
Remove the clc and clear all and save the resulting function in powermat1.m
  1 件のコメント
Walter Roberson
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

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeNumerical Integration and Differentiation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by