please make my code easier

7 次查看(过去 30 天)
Aram
Aram 2013-7-12
Hi guys,
below I have a code which with the input of K and N and NGTNo1, calculates a formula. it works properly but the problem is that it lasts too long. Any suggestion to make it faster?
G=zeros(5000,5000);
K=1;
for i=1:11293
A=N(i,1:5000);
B=NGTNo1(i,:);
F=zeros(5000,5000);
for n=1:K
C=B(n);
D=N(C,1:5000);
E=((A-D)'*(A-D))/K;
F=F+E;
end
G=F+G;
end
best regards, Aram
  1 个评论
Matt Kindig
Matt Kindig 2013-7-12
编辑:Matt Kindig 2013-7-12
While it's not clear the size of NGTNo1, from the code it is clear that N is at least 11293x5000, resulting in 5.6465e7 elements. If these are doubles, this occupies 4.5e8 bytes, or ~431 MB, of memory. This is a rather large matrix for Matlab, and thus you might be running into memory limitations, which would tend to slow down your program.
You might want to examine the size of N and NGTNo1 (using the 'whos' command), and compare it to the memory information given by the memory() function. My guess is that you are nearing the "Maximum possible array" size for your system.
I especially imagine that the line:
E = ((A-D)'*(A-D))/K;
is rather memory-intensive, as there are several temporary matrices that must be created here. You might want to split this calculation into several lines to avoid this. You could also create a new variable H = A-D to use in the calculation of E. I'm actually not sure whether the JIT accelerator is smart enough to recognize that A-D is calculated twice in this line, and do this substitution internally.

请先登录,再进行评论。

采纳的回答

Matt J
Matt J 2013-7-12
编辑:Matt J 2013-7-12
K=1;
N=N(:,1:5000).';
NGTNo1=NGTNo1(:,1:K);
G=0;
for n=1:K
A=N;
C=NGTNo1(:,n);
D=N(:,C);
AmD=(A-D);
G=G+AmD*AmD.';
end
G=G/K;

更多回答(2 个)

Aram
Aram 2013-7-12
Thanks Matt but there is an error in D=N(C,:). also I didn't realized why you wrote sqrt(K). It should it should simply divided by K.
regards, Aram
  1 个评论
Matt J
Matt J 2013-7-12
编辑:Matt J 2013-7-12
Try again, Aram. I've edited the code. The sqrt(K) is squared implicitly in the expression AmD*AmD.', but I've changed that part anyway.

请先登录,再进行评论。


Aram
Aram 2013-7-12
That's extremely safe and fast. thanks Matt :)
  1 个评论
Matt J
Matt J 2013-7-12
编辑:Matt J 2013-7-12
Aram, since you're new to the board I can see that you don't know about Accept-clicking answers. Please accept-click mine (the one with the actual solution in it) and consider also accept-clicking Star Strider's in one of your earlier questions
if it helped you.

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by