Evaluating function on an array of values

22 ビュー (過去 30 日間)
Andrea Stanghellini
Andrea Stanghellini 2021 年 4 月 5 日
編集済み: Andrea Stanghellini 2021 年 4 月 5 日
I have problems with this piece of code:
f=@(x) (exp(x)-exp(-x))./(exp(1)-exp(-1))-x;
N=5;
x=linspace(0,1,N+1);
X=x(2:N);
f(X)
I would like in output an array with the evalueation of the function at each point of the vector but matlab returns me an error:
ERROR message
Array indices must be positive integers or logical values.
Error in test>@(x)(exp(x)-exp(-x))./(exp(1)-exp(-1))-x (line 1)
f=@(x) (exp(x)-exp(-x))./(exp(1)-exp(-1))-x;
Error in test (line 5)
f(X)
Where is my mistake? Do I have to install some specific package?

採用された回答

Rik
Rik 2021 年 4 月 5 日
There are several problems here. The main one is that you are using matrix operations instead of element-wise division. In this case it doesn't matter much (as the divisor is a scalar), but it is a good habit to use ./ and .* when dealing with arrays.
The other issue is that several of the variables in your code are not defined, so we don't know what size they have. It looks like you mean X=xx(2:N) instead of X=x(2:N).
  3 件のコメント
Rik
Rik 2021 年 4 月 5 日
f=@(x) (exp(x)-exp(-x))./(exp(1)-exp(-1))-x;
N=5;
x=linspace(0,1,N+1);
X=x(2:N);
f(X)
ans = 1×4
-0.0287 -0.0505 -0.0583 -0.0443
Did you create a variable with the name exp?
Andrea Stanghellini
Andrea Stanghellini 2021 年 4 月 5 日
編集済み: Andrea Stanghellini 2021 年 4 月 5 日
No I didn't but I solve the problem, thank you so much.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by