Need help with central difference method..

12 Ansichten (letzte 30 Tage)
James
James am 4 Okt. 2013
Kommentiert: James am 4 Okt. 2013
I am very new to matlab and this is homework so I would like to just keep it simple and within the scope of what I know.. but I'm trying to plot a central difference derivative of a function as well as that function on the same figure.. Basically nothings showing up.. Here's my code:
function [void] = Task_2 clear all close all
% define numerical grid a = -3; b = 8; npt = 25; x = linspace(a,b,npt); h = abs(x(2)-x(1))^2;
% function definition f = x .* sin(x);
x_2 = linspace(a+(b-a)/npt, b-(b-a)/npt,npt-2); Dom_df = [a+(b-a)/npt,x_2] for i=2:npt-1 df(i-1) = (f(i-1)-2*f(i)+f(i+1))/h^2; end
figure(1)
set(gca,'FontSize',18) plot(x_2,df(i-1),'LineWidth',1,'MarkerSize',100) title('Random plot') legend('xsin(x)','Location','NorthWest')
I've created the x_2 vector because I know x has 25 entries while df only has 23... But yeah.. Other than the random crap that might be lying around, does anyone know why I'm not getting a plot?
Thanks!

Antworten (2)

A Jenkins
A Jenkins am 4 Okt. 2013
Perhaps you mean:
plot(x_2,df,'LineWidth',1,'MarkerSize',100)
instead of:
plot(x_2,df(i-1),'LineWidth',1,'MarkerSize',100)

Image Analyst
Image Analyst am 4 Okt. 2013
Because you put (i-1) after df so you're just plotting the same y value all the time. Plus your marker size is way way too big - it will be off the chart!
plot(x_2, df, 'bd-', 'LineWidth',2, 'MarkerSize',10)
  3 Kommentare
James
James am 4 Okt. 2013
even if I fix that, it still doesn't plot anything :/
James
James am 4 Okt. 2013
Bearbeitet: James am 4 Okt. 2013
after adding 'bd-', I see that it is indeed plotting a straight horizontal line... but that shouldn't be right.. I'm guessing something is wrong with my iteration.. do you know what's going on?
By the way, I checked the entries for df, the vector does not contain constant values... so why the hell is it plotting a straight horizontal line as if to say df(i) = constant for all i?

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by