Hi, I have this function , can help me to vectorize it? thanks
1 次查看(过去 30 天)
显示 更早的评论
f = 0;
for i = 1:n-1
fprod = 1;
for j = max (i-1,1) : min(i+1,n)
fprod = fprod * x(j)^3;
end
f = f + fprod;
end
0 个评论
回答(1 个)
Anthony Barone
2018-10-8
I think this will work.
% % % % % CREATE MASK FOR MATRIX MULTIPLICATION % % % % %
% each column computes the summation for 1 element of 'fprod'
% get probnlem size (i.e., numel(x))
nx = numel(x);
% reduce n if it is needlessly large.
n = min(nx+1,n);
% build upper half of mask
mask = true(max(nx,n-1),n-1);
mask = tril(mask);
% crop edge of upper half if needed
if nx > n-1
mask = mask(1:end-(nx-n+1),:);
end
% add in lower half
mask = [mask;flipud(mask(1:end-1,:))];
% % % % % MAIN MATRIX MULTIPLY % % % % %
% compute fprod using the mask
fprod = x(:)*mask;
% sum fprod to get f
f = fprod*true(nx,1);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Author Block Masks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!