function f(x)=xe^x
28 ビュー (過去 30 日間)
古いコメントを表示
Write a function my_fun.m which returns the value of f(x)=xe^x given an input x. This
function should be a function of x only.
3 件のコメント
Steven Lord
2019 年 8 月 27 日
James already discussed your parts b and c, so I just want to offer a little extra information. This is slightly more advanced than you may have learned so far, but it's something that can come in very useful when working with MATLAB.
For part a your function will work as long as the x input to my_fun is a scalar (just one number.) You could modify it ever so slightly to allow it to work on any sized array (a scalar, a vector with ten elements, a 5-by-5 matrix, a 2-by-3-by-4-by-5-by-6 array, etc.) by using the array multiplication operator .* instead of the matrix multiplication operator *. [For scalars they behave the same; for non-scalars they don't.] See the Array vs. Matrix Operations documentation page for more information.
回答 (2 件)
James Tursa
2019 年 8 月 27 日
編集済み: James Tursa
2019 年 8 月 27 日
Take a look at this loop from your code:
for j=1:length(x)
y = (1/N)*(a+((j-1)*h)); % <-- This replaces y at each step ... it doesn't sum anything up!
end
And compare it to the summation (3) in the instructions. Two problems: You are not calling your function, and you are not summing anything up. You should be summing up f(xj) values (N of them) and then dividing that sum by N according to the (3) formula. So the loop should be something like this instead:
for j=1:N % <-- Use the limits in the (3) formula
y = y + my_fun(a+(j-1)*h); % <-- Sums up individual calculations into y
end
y = y/N;
You don't need (or want) that x-linspace(etc) call.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で General Applications についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!