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

1 Ansicht (letzte 30 Tage)
Andres Novoa
Andres Novoa am 7 Okt. 2018
Beantwortet: Anthony Barone am 8 Okt. 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

Antworten (1)

Anthony Barone
Anthony Barone am 8 Okt. 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);

Kategorien

Mehr zu Author Block Masks finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by