plotting a function from an m file

30 ビュー (過去 30 日間)
Georgia Hastie
Georgia Hastie 2019 年 9 月 18 日
編集済み: Rik 2019 年 9 月 19 日
I've set up this function representing a sum in an m. file:
function[fx]=f(x,N)
n_fac=1;
sum=1;
for n=1:N
n_fac=n_fac*n;
sum=sum+(x^n)/n_fac
end
fx=sum
end
And I want to plot this function using the vector x = -2:0.5:5, but when I do the command plot(x,f(x,100) (where N = 100), then it gives me an error output, that says:
Not enough input arguments.
Error in f (line 7)
for n=1:N
Error in appm2360homework3 (line 8)
plot(x,f(x))
How do I go about creating a plot from my m. file function?

回答 (1 件)

Rik
Rik 2019 年 9 月 18 日
You forgot to add 100 in your actual code:
plot(x,f(x,100))
You should avoid using sum as a variable name, because it shadows the internal function, which can lead to strange behavior. Also, you forgot to use the layout tools to make your code more readable and you forgot to write comments in your code.
  2 件のコメント
Georgia Hastie
Georgia Hastie 2019 年 9 月 18 日
OK, I fixed those two things. I changed my sum variable to S and I included 100 in my code plot(f(x,100)), but now it's giving me this message:
Error using ^ (line 51)
Incorrect dimensions for raising a matrix to a power. Check
that the matrix is square and the power is a scalar. To
perform elementwise matrix powers, use '.^'.
Error in f (line 9)
S=S+(x^n)/n_fac
Error in appm2360homework3 (line 7)
plot(x,f(x,100))
Rik
Rik 2019 年 9 月 19 日
Replace ^ and / by .^ and ./ to make sure you are using element wise operations instead of array operations.
And why did you remove the first x in your call to plot?

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

カテゴリ

Help Center および File ExchangeDirected Graphs についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by