vectorize a loop with product and sum operations

2 ビュー (過去 30 日間)
Francesco
Francesco 2014 年 2 月 11 日
回答済み: Francesco 2014 年 2 月 11 日
Hi all,
I come with a question about vectorization. Suppose I have to run a code equivalent to the following
x = 1:4;
v = rand(1,10);
for i = 1:length(x)
k(i,:) = x(i)*v + x(i)
end
when you have a combined product and sum operations for each iteration.
Basic solution I can come up with is the following:
k = bsxfun(@times,x',v) + repmat(x',1,6); k = x'*v + repmat(x',1,6); % equivalent to before
Does this make any sense in terms of true vectorization? Which is the best way to vector the code? I guess for this case there is a specific "easy" answer while in some other cases more careful mathematical analysis of the formulas should be performed in order to get a "smart" vectorization.
Any comment and answer is more than welcome

採用された回答

Mischa Kim
Mischa Kim 2014 年 2 月 11 日
Francesco, use
bsxfun(@plus, x'*v, x')

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 2 月 11 日
編集済み: Azzi Abdelmalek 2014 年 2 月 11 日
x = 1:4
v = rand(1,10)
out1=bsxfun(@times,repmat(v,4,1),x')
out=bsxfun(@plus,out1,x')
%OR
x = 1:4
v = rand(1,10)
out2=bsxfun(@(ii,jj) ii.*jj+jj,repmat(v,4,1),x')

Francesco
Francesco 2014 年 2 月 11 日
Thank you very much for your kind and prompt replies. It seems to me that your solutions suggest that we can still vector loop iterations, maybe with some more complex product, sum, ... complex operations by combining a series of bsxfun operations while still gaining in execution time.
If I had an exponential and maybe a division in the code, then I guess I could add an exp calculation and a division by still using bsxfun
x = 1:4;
v = rand(1,10);
for i = 1:length(x)
k(i,:) = (exp(x(i)*v) + x(i))/x(i)
end
would the previous hints still make the trick or can one still do it in a single line of code?
Best and thanks again!

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by