Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
矢量化Matlab-如何无环矢量化高斯函数(代码)_Matlab_Vectorization_Gaussian_Numerical Methods_Numerical Integration - Fatal编程技术网

矢量化Matlab-如何无环矢量化高斯函数(代码)

矢量化Matlab-如何无环矢量化高斯函数(代码),matlab,vectorization,gaussian,numerical-methods,numerical-integration,Matlab,Vectorization,Gaussian,Numerical Methods,Numerical Integration,我写了一个函数,用高斯求积规则计算积分。我需要矢量化最后2行,不使用循环。有什么想法吗 function Q = gauss5(f,a,b,n) % Divide the interval into n parts y = linspace(a,b,n); % Create function to use arrayfun % Sum up the result from the arrayfun with function Fun on particular

我写了一个函数,用高斯求积规则计算积分。我需要矢量化最后2行,不使用循环。有什么想法吗

function Q = gauss5(f,a,b,n)
    % Divide the interval into n parts
    y = linspace(a,b,n);
    % Create function to use arrayfun
    % Sum up the result from the arrayfun with function Fun on particular
    % intervals, the first argument is array y without the last value, and
    % the second argument is the array y without the first value
    a  = (y(1:end-1));
    b = (y(2:end));
    % coefficients - some random numbers
    c = [1 2 3 4 5];
    % nodes - random numbers too
    x = [1 1 1 1 1];
    % calculate b-a
    w = b-a;
    % sum up the result
    Q = 0;
    for i=1:n-1
    Q = Q + sum((w(i)*c.*feval(f,((w(i)*x)+a(i)))));
    end
end

如果您的
f
可以获取一个数组作为输入,则可以替换此数组:

% sum up the result
Q = 0;
for i=1:n-1
    Q = Q + sum((w(i)*c.*feval(f,((w(i)*x)+a(i)))));
end
据此:

wxa = bsxfun(@plus,bsxfun(@times,w,x(:)),a);
Qs = bsxfun(@times,w,c(:)).*feval(f,wxa);
Q = sum(Qs(:))
或者,如果您有Matlab 2016b或更高版本,只需:

Qs = w.*c(:).*feval(f,w.*x(:)+a);
Q1 = sum(Qs(:));

f可以是不同的函数吗?而且
n
是否总是小于
a
b
的长度?