【发布时间】:2016-12-20 15:59:16
【问题描述】:
我正在为 matlab 中的 picard 方法编写程序。这需要对一个函数进行多次迭代,该函数被替换为待积分多项式。
现在我有一个带有符号 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
提前致谢!
【问题讨论】:
-
你的其余代码在哪里?
polynomial、degree等最初是如何定义的?请提供一个最小的工作示例,以便其他人可以尝试复制您的错误?此外,polynomial已经是x中的symfun- 为什么要调用y(1) = symfun(polynomial, x);而不是y(1) = polynomial;? -
我用完整的代码更新了它。
y(1) = symfun(polynomial,x);更像是一种尝试,因为没有它也无法工作。但是,是的,这没有意义。
标签: matlab numerical-methods differential-equations