function f(x)=xe^x
33 views (last 30 days)
Show older comments
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 Comments
Steven Lord
on 27 Aug 2019
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.
Answers (2)
James Tursa
on 27 Aug 2019
Edited: James Tursa
on 27 Aug 2019
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 Comments
See Also
Categories
Find more on General Applications in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!