Hi, I have this function , can help me to vectorize it? thanks
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
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);
0 commentaires
Voir également
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!