MATLAB中diff函数使用遇到问题求助 100
H = [13.11 15.79 25.79 30.53 33.16 35.79 38.42 6 7];
y = polyfit(B,H,3);
y3=polyval(y,B);
plot (B,y3);
n = length(y);
ss = '';
for k = 1:n
yy = num2str(y(k));
ss = strcat(ss,['+' '(' yy ')' '*' 'x' '^' num2str(n+1-k)]);
end
dss = diff(ss,'x');
ddss = diff(dss,'x');
xx = solve(ddss);
xy = eval(subs(dss,'x',xx));
[dmax,index] = max(xy);
x = xx(index);
y = eval(subs(ss,'x',x))
x = eval(x)这是我的代码,他提示x必须为正整数,我这个是字符串,但是不用字符串形式,x就是自变量定义不了 展开
MATLAB中的diff函数需要的参数都得是sym类型的符号变量,有一些比较旧的教科书中使用的是字符串变量,与现在的新版本的MATLAB不符,字符串变量的用法被移除了,所以出错。
代码应该做如下修改以达预期效果:
①把第12行“dss = diff(ss,'x');”改为“syms x;dss=diff(eval(ss),x);”
②第13行“ddss = diff(dss,'x');”改为“ddss = diff(dss,x);”
③第18行“y = eval(subs(eval(ss),'x',x))”改为“y = eval(subs(eval(ss),sym('x'),x))”
修改后的代码还是19行,代码截图和运行效果如下:
B = [0.1:0.1:0.9];
H = [13.11 15.79 25.79 30.53 33.16 35.79 38.42 6 7];
y = polyfit(B,H,3);
y3=polyval(y,B);
plot (B,y3);
n = length(y);
ss = '';
for k = 1:n;
yy = num2str(y(k));
ss = strcat(ss,['+' '(' yy ')' '*' 'x' '^' num2str(n+1-k)]);
end
;
syms x;dss = diff(eval(ss),x);
ddss = diff(dss,x);
xx = solve(ddss);
xy = eval(subs(dss,'x',xx));
[dmax,index] = max(xy);
x = xx(index);
y = eval(subs(eval(ss),sym('x'),x))
;disp(y);
x = eval(x);disp(x);