Remove the need for nested for loop
Show older comments
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';
Accepted Answer
More Answers (1)
Kevin Phung
on 12 Jan 2019
Edited: Kevin Phung
on 12 Jan 2019
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
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!