How to vectorize this "for" loop, or parallel it.

1 view (last 30 days)
chen
chen on 23 Jan 2014
Commented: chen on 23 Jan 2014
fun = @(x,y) x + x.*y;
N = 1e3;
K = zeros(N);
for i = 1:N
for j = i:N
K(i,j) = fun(i, j);
end
end

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 23 Jan 2014
Edited: Azzi Abdelmalek on 23 Jan 2014
fun = @(x,y) x + x.*y;
N=1000
[y,x]=meshgrid(1:N,1:N);
out=triu(fun(x,y))
  2 Comments
Azzi Abdelmalek
Azzi Abdelmalek on 23 Jan 2014
Edited: Azzi Abdelmalek on 23 Jan 2014
N=4000;
tic
fun = @(x,y) x + x.*y;
[y,x]=meshgrid(1:N,1:N);
f=triu(fun(x,y));
toc
tic
K = zeros(N);
for i = 1:N
for j = i:N
K(i,j) = fun(i, j);
end
end
toc
isequal(f,K)
Elapsed time is 0.193062 seconds.
Elapsed time is 2.421795 seconds.

Sign in to comment.


Matt J
Matt J on 23 Jan 2014
Edited: Matt J on 23 Jan 2014
K=(1:N).'*(2:N+1);
  1 Comment
Matt J
Matt J on 23 Jan 2014
Or,
K=bsxfun(@times,(1:N).', 2:N+1);
On my machine, this is faster than straight multiplcation for some weird reason!!

Sign in to comment.

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!