フィルターのクリア

I'm trying to make a Simpsons Rule Function Myself

1 回表示 (過去 30 日間)
Jack Bush
Jack Bush 2018 年 12 月 13 日
コメント済み: Walter Roberson 2018 年 12 月 15 日
I've had a few attempts at this question and have developed my answer further each time. If people wouldn't mind giving feedback or correcting my code that'd be great.
This is the question:
Simpsons Rule Question Only.JPG
and the code I have written to answer this is, there is more to th question but this is just my code for the first bit:
function [y] =MPR_Asgn4_Q4a_26024405(f,a,b,n)
h=(b-a)/n;
x=zeros(1,n+1);
x(1)=a;
x(n+1)=b;
s1=0;
s2=0;
s3=0;
for k = 2:n
x(k)=a+h*(1i-1);
end
for k=1:n/2
s1= s1 + f(x(2*1i-1));
end
for k=1:n/2
s2=s2+f(x(2*1i));
end
for k= 1:n/2
s3 = s3 +f(x(2*1i+1));
end
y = (h/3)*(s1+(4*s2)+s3);
disp(y);
end
  2 件のコメント
Omer Yasin Birey
Omer Yasin Birey 2018 年 12 月 14 日
Hi Jack,
I tried to understand your code and the formula together. However, firstly I believe your "i" usages are quite wrong. If you put "i" or "j" without multiplication sign (*) that gives complexity to the number. However, if Im not wrong there is no calculations in complex domain here. Secondly, you are using loops without using the loop indexes maybe you meant "k" instead of "i"?
Walter Roberson
Walter Roberson 2018 年 12 月 15 日
Please do not close questions that have answers.

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

採用された回答

Omer Yasin Birey
Omer Yasin Birey 2018 年 12 月 14 日
編集済み: Omer Yasin Birey 2018 年 12 月 14 日
Hi Jack,
I fixed your code as much as I can. You can use the code below:
function [y] =MPR_Asgn4_Q4a_26024405(f,a,b,n)
x = linspace(a,b,n);
x(1)=a;
x(n+1)=b;
h=(b-a)/n;
s1=0;
s2=0;
s3=0;
%First if statements is to check if f is an anonymous function
%or an array.
if length(f) > 1%array state
%if it is a array your sub intervals will be the length of array
%So you have to update it.
n = length(f)-1;
h=(b-a)/n;
for k=3:2:length(f)-2
s1= s1 + 2*f(k);
end
for k=2:2:length(f)
s2=s2+f(k);
end
s3 = f(length(f));
y = (h/3)*(f(1)+(2*s1+(4*s2)+s3));
else%anonymous function state
for k=3:2:length(f)-2
s1= s1 + 2*f(x(k));
end
for k=3:2:length(f)
s2=s2+f(x(k));
end
s3 = f(length(f));
y = (h/3)*(f(x(1))+(2*s1+(4*s2)+s3));
end
disp(y);
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by