Why am I getting "Undefined function or variable" when I use an exponential in the function?

My code worked for other functions, but as soon as I use the exponential function, I am getting an error saying that "I" is undefined, and I honestly have no idea why it's giving me an error only for the exponential function.
a = 0;
b = 1;
N = 10;
f = @(x) exp(-x);
h=(b-a)/N;
j = 0;
x=linspace(a,b,N);
for i = 1:N-1
j=j+f((2*i+1)/2)*x;
end
answer1 = sum(I)

回答 (1 件)

James Tursa
James Tursa 2019 年 4 月 11 日
There is no "I" variable in your code. Hence the error.

5 件のコメント

When I defined the code as:
a = 0.001;
b = 1/2;
N = 10;
f = @(x) cos((pi*cos(x))/2).^2.*csc(x);
h=(b-a)/N;
j = 0;
x=linspace(a,b,N);
for i = 1:N-1
j=j+f((2*i+1)/2)*x;
end
answer1 = sum(I)
It was not giving me that error. Also tried things such as x^2 and cos(x), and I wasn't getting that error then.
James Tursa
James Tursa 2019 年 4 月 11 日
編集済み: James Tursa 2019 年 4 月 11 日
Look at your code again. There is no "I" variable defined. Here is what I get when I run your above cos( ) code from a clean workspace:
Undefined function or variable 'I'.
You probably have a left-over "I" variable in your workspace from a previous calculation. Sometimes it is there and sometimes it isn't so you get the error "randomly" or at least unexpectedly. The solution is to fix your code and define all the variables that your code uses (including the "I" variable) in your code.
Interestingly enough, I definied my f for a different problem and got the error initally stated, but the new problem doesn't have an exponential in it.
f = @(x) cos(4*cos(x)+x);
James Tursa
James Tursa 2019 年 4 月 11 日
What does the exponential have to do with your problem of "I" not being defined?
John D'Errico
John D'Errico 2019 年 4 月 11 日
I wonder if it is possible Nocholas has created a script of function named exp?

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

カテゴリ

ヘルプ センター および File ExchangeGet Started with MATLAB についてさらに検索

タグ

質問済み:

2019 年 4 月 11 日

コメント済み:

2019 年 4 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by