我正在为matlab中的picard方法编写一个程序。这需要对要被积分多项式替换的函数进行多次迭代。
现在我有一个已有的带有syms x的多项式,它由一个向量a定义:
for i = 1:degree+1
polynomial = symfun(polynomial + a(i) *x^(i-1), x);
end
syms t;
y = symfun( zeros(1,maxIterations+1),x);
y(1) = polynomial;
for i = 2: maxIterations
substitute = subs(polynomial, x, y(i-1));
y(i) = symfun(x0 + int( substitute, t), x); %for some predefined x0
end但是当我尝试使用y(1) = symfun(polynomial,x);时,它失败了,给出了一个错误:
无效的索引或函数定义。在定义函数时,请确保参数是符号变量,函数的主体是SYM表达式。索引时,输入必须是数字、逻辑或“:”。
但是,既然polynomial只是一个辛函数,为什么不能将它分配给向量y中的一个槽呢?在定义时,我已经尝试过使用feval(),而不是使用symfun(),但是到目前为止没有什么效果。
完整代码:
%%Input
prompt = 'What is the degree of the polynomial? \n ';
degree = input(prompt);
a = zeros(degree+1,1);
for i = 1:degree+1
a(i) = input(['Enter value of coefficient a_' num2str(i-1) ': ']);
end
prompt = 'What is the number of iterations? \n ';
maxIterations = input(prompt);
prompt = 'What is the value of x0? \n ';
x0 = input(prompt);
%%Computing Integrated Vector
aInt = [0];
for i = 1:degree+1
aInt(i+1) = a(i)/(i);
end
fprintf('x0');
for i = 1: degree+1
fprintf( [' + ' num2str(aInt(i+1)) ' x^' num2str(i)] );
end
fprintf('\n');
syms x;
polynomial = 0;
for i = 1: degree+1
polynomial = symfun(polynomial + a(i) * x ^(i-1), x);
end
%Picard Method
syms t;
syms y;
y = symfun( zeros(maxIterations+1,1), x );
y(1) = polynomial;
for i = 2: maxIterations
substitute = subs(polynomial, x, y(i-1));
y(i) = symfun(x0 + int( substitute,t ), t);
end
for i = 1:maxIterations
fprintf(['x_' num2str(i-1) ' = ' y(i), ' \n']);
end提前感谢!
发布于 2016-12-21 11:48:41
修好了!这是工作密码。(其中可能仍有轻蔑的错误)。这个错误没有正确地定义polynomial,因为我首先使用了syms(polynomial),它导致多项式的和将‘多项式’作为一个变量。考虑picard方法,还修正了一些轻微的错误,如y(1)的定义。
%%Input
prompt = 'What is the degree of the polynomial? \n ';
degree = input(prompt);
a = zeros(degree+1,1);
for i = 1:degree+1
a(i) = input(['Enter value of coefficient a_' num2str(i-1) ': ']);
end
prompt = 'What is the number of iterations? \n ';
maxIterations = input(prompt);
prompt = 'What is the value of x0? \n ';
x0 = input(prompt);
%%Computing Integrated Vector
aInt = [0];
for i = 1:degree+1
aInt(i+1) = a(i)/(i);
end
%%vector print
fprintf('x0');
for i = 1: degree+1
fprintf( [' + ' num2str(aInt(i+1)) ' x^' num2str(i)] );
end
fprintf('\n');
syms x;
polynomial = 0;
for i = 1: degree+1
polynomial = polynomial + symfun(a(i) * x ^(i-1), x);
end
%Picard Method
syms t;
syms y;
y = sym( 'y', [1 maxIterations] );
y(1) = x0;
for i = 2: maxIterations
substitute = subs(polynomial, x, y(i-1));
y(i) = symfun(x0 + int( substitute, t ), t);
end
for i = 1:maxIterations
fprintf('The iteration y_%d = %s \n',(i-1), y(i))
end
%plot graphshttps://stackoverflow.com/questions/41246418
复制相似问题