Quick way to find element by element difference betwen two vectors

3 ビュー (過去 30 日間)
superkevin2009
superkevin2009 2016 年 8 月 2 日
回答済み: James Tursa 2016 年 8 月 2 日
I have two vectors, roughly of size 5000 each. Let’s call them vec1 and vec2. I would like a matrix of size 5000 x 5000 where the (i,j)th element represents the absolute difference between the ith element of vec1 and the jth element of vec2.
I've written my code as follows but it's very slow. I may need to expand the dimensionality of the problem so a quick way to do this would be much appreciated. Does anyone have a better way to do this?
mat=zeros(size(vec1,1),size(vec2,2));
for i=1:size(mat,1)
for j=1:size(mat,2)
mat(i,j)=abs(vec2(j)-vec1(i));
end
end

採用された回答

James Tursa
James Tursa 2016 年 8 月 2 日
mat = abs(bsxfun(@minus,vec2(:).',vec1(:)));

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeParallel Computing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by