如下代码,想把4个y代入这个fun函数中求积分,但一个个求太麻烦了,想一次性求出来,要如何改
y=[2.916;88.631;0.68;11.137];
fun= @(x)exp(y(1)*cos(x))/(2*pi);
y1 = integral(fun,0,360) ;
fun= @(x)exp(y(2)*cos(x))/(2*pi);
y2 = integral(fun,0,360) ;
fun= @(x)exp(y(3)*cos(x))/(2*pi);
y3 = integral(fun,0,360) ;
fun= @(x)exp(y(4)*cos(x))/(2*pi);
y4 = integral(fun,0,360) ;
我试着用for循环,但是这种写法会把4个值加在一起,是哪里有问题吗
y=[2.916;88.631;0.68;11.137];
n=numel(y)
for i=1:1:n
fun= @(x)exp(y(i)*cos(x))/(2*pi);
y0 = integral(fun,0,360) ;
end
这样就可以了:
%方法1
y=[2.916;88.631;0.68;11.137];
ret = [];
for i=1:length(y)
fun= @(x)exp(y(i)*cos(x))/(2*pi);
ret=[ret integral(fun,0,360)];
end
%方法2
%直接利用矩阵运算
y=[2.916;88.631;0.68;11.137];
fun= @(x)exp(y*cos(x))/(2*pi);
ret=integral(fun,0,360,'ArrayValued',true);