MATLAB: Elegant way to create dynamically an array inside a for loop

arraydynamic array creationelegant wayfor loopvectorvector indexing

Check the following piece of code.
r = magic(5);
w = bartlett(5);
for j=1:10
b1(j)=sum(r(1,:).*w'*j);
b2(j)=sum(r(2,:).*w'*j);
b3(j)=sum(r(3,:).*w'*j);
b4(j)=sum(r(4,:).*w'*j);
b5(j)=sum(r(5,:).*w'*j);
end
b = [b1;b2;b3;b4;b5];
each b1,b2,b3,b4,b5 is a vector of size 1×10 and the final result I am looking for is a vector b of size 5×10 .
I was wondering if there is a more robust way to create b rather than the paradigm above.

Best Answer

d=sum(bsxfun(@times,repmat(bsxfun(@times,r',w)',1,1,10),reshape(1:10,1,1,[])),2)
b=d(:,:);