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

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

답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2014년 1월 23일
편집: Azzi Abdelmalek 2014년 1월 23일

0 개 추천

fun = @(x,y) x + x.*y;
N=1000
[y,x]=meshgrid(1:N,1:N);
out=triu(fun(x,y))

댓글 수: 2

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.
chen
chen 2014년 1월 23일
Thanks a lot !

댓글을 달려면 로그인하십시오.

Matt J
Matt J 2014년 1월 23일
편집: Matt J 2014년 1월 23일

0 개 추천

K=(1:N).'*(2:N+1);

댓글 수: 1

Or,
K=bsxfun(@times,(1:N).', 2:N+1);
On my machine, this is faster than straight multiplcation for some weird reason!!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Parallel Computing Toolbox에 대해 자세히 알아보기

질문:

2014년 1월 23일

댓글:

2014년 1월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by