Hi, I have this function , can help me to vectorize it? thanks

1 vue (au cours des 30 derniers jours)
Andres Novoa
Andres Novoa le 7 Oct 2018
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

Réponses (1)

Anthony Barone
Anthony Barone le 8 Oct 2018
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);

Catégories

En savoir plus sur Author Block Masks dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by