Remove the need for nested for loop

3 ビュー (過去 30 日間)
Jack Hillyer
Jack Hillyer 2019 年 1 月 11 日
コメント済み: Star Strider 2019 年 1 月 12 日
Hi, so I have a vector and I am trying to create a matrix containing the difference between the vector elements. I am currently using a nested for loop, but need to speed it up (the vector has 9000 elements). Is there any way of doing this?
I have a vector a
b=length(a);
for i=1:b
for j=i+1:b
da=a(i)-a(j);
end
end
da=da+da';

採用された回答

Star Strider
Star Strider 2019 年 1 月 11 日
I am not certain of the result you want.
Try this:
a = randi(9, 1, 5); % Create Vector
da = bsxfun(@minus, a(1:end-1), a(2:end)'); % Matris Of Differences
  2 件のコメント
Jack Hillyer
Jack Hillyer 2019 年 1 月 11 日
Hi, sorry for being vague, maybe I should have given an example.
If a= [1 2 3]'
da=[0 1 2; -1 0 1; -2 -1 0]
Thank you for the help!
Star Strider
Star Strider 2019 年 1 月 12 日
My pleasure!
The example definitely helps.
A slight revision of my previous code:
a = [1 2 3];
da = bsxfun(@minus, a, a') % Matrix Of Differences
produces:
da =
0 1 2
-1 0 1
-2 -1 0
that appears to be the desired result.

サインインしてコメントする。

その他の回答 (1 件)

Kevin Phung
Kevin Phung 2019 年 1 月 12 日
編集済み: Kevin Phung 2019 年 1 月 12 日
a = [1 2 3];
da = zeros(numel(a));
for i = 1:numel(a)
da(:,i) =a(i) - a
end
You will save the program some time by predefining the size of da before the loop instead of constantly adding columns to it.
Hope this helps

カテゴリ

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

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by