function f(x)=xe^x
Ältere Kommentare anzeigen
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 Kommentare
Steven Lord
am 24 Aug. 2019
This sounds like a homework assignment. If it is, show us what you've done to try to solve the problem and ask a specific question about where you're having difficulty and we may be able to offer some guidance.
Deanna Jaramillo
am 27 Aug. 2019
Steven Lord
am 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.
Antworten (2)
Star Strider
am 24 Aug. 2019
1 Stimme
James Tursa
am 27 Aug. 2019
Bearbeitet: James Tursa
am 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.
Kategorien
Mehr zu Programming finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


