Cost matrix from an array without for loop.

1 回表示 (過去 30 日間)
daniel adams
daniel adams 2021 年 9 月 29 日
編集済み: the cyclist 2021 年 9 月 29 日
Hi I want to create a matrix with entries the absolute value between each point in an array.
My array is called domain, and it has length grid_number.
I have done this in the below code, however I have used a for loop. It takes a long time to run when grid_number is large. Is there a neat way to do this?
for i=1:grid_number
for j=1:grid_number
cost(i,j)=abs(domain(i)-domain(j))
end
end

採用された回答

the cyclist
the cyclist 2021 年 9 月 29 日
編集済み: the cyclist 2021 年 9 月 29 日
You can use implicit expansion to subtract the two vector from each other, by transposing one of them.
cost = abs(domain-domain.');
If you have an older version of MATLAB, that does not support implicit expansion, you can use
cost = abs(bsxfun(@minus,domain,domain'));

その他の回答 (1 件)

Matt J
Matt J 2021 年 9 月 29 日
編集済み: Matt J 2021 年 9 月 29 日
cost=abs( domain(:)-domain(:).' );

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by