I need help plotting this, i Cant figure out what is wrong

조회 수: 1 (최근 30일)
ragheed idrees
ragheed idrees 2019년 6월 5일
댓글: ragheed idrees 2019년 6월 6일
fun = @(x) x.^3 - 10*x.^2 + 16*x +80;
a = 0;
b = 6;
for n = [2, 3, 4, 5, 6, 8, 10, 12, 14, 16, 18, 20]
I = A9P1TRAPIdrees(fun,a,b,n);
err = abs((372-I)/372)*100;
fprintf('n = %d value=%f error= %f\n', n, I, err);
end
subplot(3,1,1); %f(x) vs. x
fplot(fun,[0 6])
title({['Ragheed Idrees ',datestr(now)];'';'f(x) vs x)'})
xlabel('x')
ylabel('f(x)')
subplot(3,1,2); %Integral vs number of sugments
plot(n,I)
title('Integral vs number of sugments')
xlabel('number of segments')
ylabel('Integral')
subplot(3,1,3); %Percent error vs number of sugments
loglog(n,err)
title('Percent error vs number of sugments')
xlabel('number of segments')
ylabel('Percent Error')
-----------------------------------------------------------------------------A9P1TRAPIdrees-------------------------------------------------------------------------------------------------------------
function I = A9P1TRAPIdrees(fun,a,b,n)
%this function uses the trapezoidal rule to integrate a function with given
%boundaries and number of segments
%defining the output
h = (b-a)/n;
s=0.5 * (fun(a)+fun(b));
I=0;
for jj = 1 : n-1
s = s +fun(a + jj*h);
end
I = h *s;
it gives me a warning "Function behaves unexpectedly on array inputs. To improve performance, properly vectorize your function to return an output with the same size
and shape as the input arguments. "
and the last 2 subplots wont plot!

채택된 답변

Walter Roberson
Walter Roberson 2019년 6월 6일
fun = @(x) x^3 - 10*x.^2 + 16*x +80;
should be
fun = @(x) x.^3 - 10*x.^2 + 16*x +80;
  댓글 수: 5
Walter Roberson
Walter Roberson 2019년 6월 6일
nvals = [2, 3, 4, 5, 6, 8, 10, 12, 14, 16, 18, 20];
numn = length(nvals);
err = zeros(1, numn);
I = zeros(1, numn);
for nidx = 1 : numn
n = nvals(nidx);
I(nidx) = A9P1TRAPIdrees(fun,a,b,n);
err(nidx) = abs((372-I(nidx))/372)*100;
fprintf('n = %d value=%f error= %f\n', n, I(nidx), err(nidx));
end
subplot(3,1,1); %f(x) vs. x
fplot(fun,[0 6])
title({['Ragheed Idrees ',datestr(now)];'';'f(x) vs x)'})
xlabel('x')
ylabel('f(x)')
subplot(3,1,2); %Integral vs number of sugments
plot(nvals, I)
title('Integral vs number of sugments')
xlabel('number of segments')
ylabel('Integral')
subplot(3,1,3); %Percent error vs number of sugments
loglog(nvals, err)
title('Percent error vs number of sugments')
xlabel('number of segments')
ylabel('Percent Error')
-----------------------------------------------------------------------------A9P1TRAPIdrees-------------------------------------------------------------------------------------------------------------
ragheed idrees
ragheed idrees 2019년 6월 6일
that checked everything, thangs again!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by