|
回复 11 # mhkmars 的帖子
3# mhkmars
要解方程,需要把x,y,z换为x(1),x(2),x(3)
本来想用strrep替换x为x(1),y为x(2),z为x(3),但是这样一来就把exp中的x也替换了,还要判断,太麻烦了
如何用符号变量,速度太慢
所以建议,你还是将x,y,z等写为x(1),x(2),x(3)
下面是我写的一个小例子,可以进行批量处理,N个变量也可以
1.用子函数- clear;clc;close all
- strf={'sin(x(1))+x(2)+x(3)^2*exp(x(1))-4',...;
- 'x(1)+x(2)*x(3)',...
- 'x(1)*x(2)*x(3)'};
- x=[1 2 3];
- fsolve(@(x)myfunex0109(x,strf),x)
复制代码- function y=myfunex0109(x,strf)
- strf=cellfun(@str2func,strcat({'@(x)'},strf'),'UniformOutput',false);
- y=arrayfun(@(x0)strf{x0}(x),1:length(strf));
复制代码
- Equation solved.
- fsolve completed because the vector of function values is near zero
- as measured by the default value of the function tolerance, and
- the problem appears regular as measured by the gradient.
- <stopping criteria details>
- ans =
- -0.0002 0.0001 2.0003
复制代码 2.用内嵌函数- function y=myex0109
- strf={'sin(x(1))+x(2)+x(3)^2*exp(x(1))-4',...;
- 'x(1)+x(2)*x(3)',...
- 'x(1)*x(2)*x(3)'};
- x0=[1 2 3];
- y=fsolve(@myfunex0109,x0);
- function y=myfunex0109(x)
- strf1=cellfun(@str2func,strcat({'@(x)'},strf'),'UniformOutput',false);
- y=arrayfun(@(x0)strf1{x0}(x),1:length(strf));
- end
- end
复制代码-
- Equation solved.
- fsolve completed because the vector of function values is near zero
- as measured by the default value of the function tolerance, and
- the problem appears regular as measured by the gradient.
- <stopping criteria details>
- ans =
- -0.0002 0.0001 2.0003
复制代码 |
评分
-
4
查看全部评分
-
|