任务
clearvars
n=input('Enter number of terms to approximate pi/4: ');
Error=zeros(1, n);
S=0;
k=0;
% Initial value of summation Error=zeros(1, n); % Memory allocation k=0;
for k=0:n-1
p=(-1)^k;
S=S+p/(2*k+1);
Error(k)=pi/4-S; % Accumulates all of Errors from all iterations k=k+1;
end
plot(1:n, Error), grid on
title(['\pi/4 Approximation of ', num2str(n), ' terms'])
ylabel('Error'), xlabel('Number of terms')
错误提示
下标索引必须为正整数类型或逻辑类型。
原因
matlab 数组的下标索引是从1开始的
修改
clearvars
n=input('Enter number of terms to approximate pi/4: ');
Error=zeros(1, n);
S=0;
k=0;
% Initial value of summation Error=zeros(1, n); % Memory allocation k=0;
for k=0:n-1
p=(-1)^k;
S=S+p/(2*k+1);
Error(k+1)=pi/4-S; % Accumulates all of Errors from all iterations k=k+1;
end
plot(1:n, Error), grid on
title(['\pi/4 Approximation of ', num2str(n), ' terms'])
ylabel('Error'), xlabel('Number of terms')