*THIS PROBLEM REQUIRES THE MATLAB CODE* This is the code i have so far but it ha
ID: 3848197 • Letter: #
Question
*THIS PROBLEM REQUIRES THE MATLAB CODE*
This is the code i have so far but it has some problems i need help fixing. Thanks
%% part a)
x = -0.7:0.7
f = (1)./(1+2.*x.^2);
% first part for n=10
for j = 1:14
su(j)=0;
for n=1:10
su(j)=su(j)+(-1)^n*2^n*x(j)^(2*n);
end
err(j)=abs(f(j)-su(j));
end
True_Relative_Error1=sum(err)
% second part for n=50
for j=1:14
sum1(j)=0;
for n=1:50
sum1(j)=sum1(j)+(-1)^n*2^n*x(j)^(2*n);
end
err1(j)=abs(f(j)-sum1(j));
end
True_Relative_Error2=sum(err1)
%% part b)
figure;
plot(x,f);
hold on
plot(x,su,'r');
legend('Actual Value','Expansion of n=10')
figure;
plot(x,f);
hold on
plot(x,sum1,'b-');
legend('Actual Value','Expansion of n=50')
title('Problem #1 Graph')
Explanation / Answer
CORRECTED MATLAB CODE
clc;
clear all;
close all;
%% part a)
x = -0.7:0.1:0.7
f = (1)./(1+2.*x.^2);
% first part for n=10
for j = 1:14
su(j)=0;
for n=1:10
su(j)=su(j)+(-1)^n*2^n*x(j)^(2*n);
end
err(j)=abs(f(j)-su(j));
end
su
True_Relative_Error1=sum(err)
% second part for n=50
for j=1:14
sum1(j)=0;
for n=1:50
sum1(j)=sum1(j)+(-1)^n*2^n*x(j)^(2*n);
end
err1(j)=abs(f(j)-sum1(j));
end
True_Relative_Error2=sum(err1)
%% part b)
figure;
plot(f);
hold on
plot(su,'r');
legend('Actual Value','Expansion of n=10')
figure;
plot(f, 'b-');
hold on
plot(sum1,'r');
legend('Actual Value','Expansion of n=50')
title('Problem #1 Graph')
Problems in the previous code
1) Step size of vector x was not defined. => x = -0.7:0.1:0.7
2) The x vector has 15 elements and f, su and sum1 vector has 14 elements in each, hence an error in size was occuring . So just put the f, su and sum1 in plot statement and you will get the output plot.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.