Can't understand this MATLAB syntax?

for i=0:255
m(i+1)=sum((0:i)'.*p(1:i+1)); end

      

Someone can explain what is happening. p is a 256 element array equal to m.

+3


source to share


2 answers


p = (0:255)';
m = zeros(1,256);
for i=0:255
    m(i+1)=sum((0:i)'.*p(1:i+1)); 

end

      

m[i+1]

contains a dot product [0,1,2,..,i]

with(p[1],...,p[i+1])

You can write it like:

p = (0:255);
m = zeros(1,256);
for i=0:255
    m(i+1)=sum((0:i).*p(1:i+1)); 

end

      



Or:

p = (0:255);
m = zeros(1,256);
for i=0:255
    m(i+1)=(0:i)*p(1:i+1)'; 

end

      

If you don't remember, this is the definition of a scalar product

+4


source


Regardless p

, you can calculate m

with:

dm = (0 : length(p) - 1)' .* p(:); % process as column vector
m = cumsum(dm);

      

Hint: write the formula for m [n], then for m [n + 1], then subtract to get the formula:



m[n+1] - m[n] = (n - 1) * p[n]

      

and this dm

.

+1


source







All Articles