Hello, I am trying to use the central difference for the function sin(2*pi*x), centered around x=0.313. I know what value should be, that is my "act" variable. If someone can help me why my for loop is messed-up, it'll be much appreciated.
CODE:
clc, clear, close all
syms x
% Actual Value
f = sin(2*pi*x);
df = diff(f,x);
x = 0.313;
true_value = 2*pi*cos(2*pi*x)
% Central Difference
for i=1:3
x = 0.313;
for h = [0.01 0.1 0.25]
df_dx(i) = (sin(2*pi*(x+h))-sin(2*pi*(x-h)))/2*h
end
end
act = (sin(2*pi*0.314)-sin(2*pi*0.312))/0.02

 採用された回答

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 3 月 19 日
編集済み: KALYAN ACHARJYA 2019 年 3 月 19 日

0 投票

-If someone can help me why my for loop is messed-up-
clc, clear, close all
syms x
% Actual Value
f=sin(2*pi*x);
df=diff(f,x);
x=0.313;
true_value=2*pi*cos(2*pi*x);
h=[0.01 0.1 0.25];
df_dx=zeros(1, length(h));
% Central Difference
for i=1:3
df_dx(i)=(sin(2*pi*(x+h(i)))-sin(2*pi*(x-h(i))))/2*h(i);
end
act=(sin(2*pi*0.314)-sin(2*pi*0.312))/0.02;
Output:
df_dx=
-0.0002 -0.0227 -0.0964
Without for loop
clc, clear, close all
syms x
% Actual Value
f=sin(2*pi*x);
df=diff(f,x);
x=0.313;
true_value=2*pi*cos(2*pi*x);
h=[0.01 0.1 0.25];
% Central Difference
df_dx=(sin(2*pi.*(x+h))-sin(2*pi.*(x-h)))./(2*h);
act=(sin(2*pi*0.314)-sin(2*pi*0.312))/0.02;
Command Window:
>> df_dx
df_dx =
-0.0002 -0.0227 -0.0964

9 件のコメント

madhan ravi
madhan ravi 2019 年 3 月 19 日
Why do you need a loop?
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 3 月 19 日
@Madhan sir, I have added the answer without loop also.
madhan ravi
madhan ravi 2019 年 3 月 19 日
編集済み: madhan ravi 2019 年 3 月 19 日
pre-allocation is essential for a loop, h(1:3) is the same as h
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 3 月 19 日
編集済み: KALYAN ACHARJYA 2019 年 3 月 19 日
Yes edited, truly thanks sir.
madhan ravi
madhan ravi 2019 年 3 月 19 日
The proper usage is
./(2*h) % use parantheses
%^---- element wise operation
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 3 月 19 日
yeah..Thanks
madhan ravi
madhan ravi 2019 年 3 月 19 日
madhan ravi
madhan ravi 2019 年 3 月 19 日
./ is not corrected yet , please by any chance don't delete this answer so that it's pretty clear how many possible mistakes can be made in this problem.
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 3 月 19 日
編集済み: KALYAN ACHARJYA 2019 年 3 月 19 日
Yes, got it sir, but for small number of iterations, there may be negligible difference.right?
>> matlab_ans_march_19
Without Pre-allocation
Elapsed time is 0.003340 seconds.
%%
>> matlab_ans_march_19
With Pre-allocation
Elapsed time is 0.002957 seconds.
Yes, prefer to use for better coding performance (always).

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by