Pergunta

I'v a nested for loop but it slows a little bit processing, how can I make the nested loops an efficient. What I need is for every value of outer loop, the inner loop continues all its iterations. However, I don't think so it affects the computations as so much the two nested loops. My second question is, is parfor loop may affect the speed or may support my phenomena?

My Code:

n=2;
for i=1:500
for jj=1:n
    A{1}=['Obj' num2str(1)];
    A{2}=['Obj' num2str(2)];
end  
end
Foi útil?

Solução

Your nested loops as they are do not exhibit any dependence on the loop parameters so you might want to reformat your code above. But in general, so long as your iterations are not dependent on each other and the number of iterations is large enough to support the delay in initializing the parallel processing, the parfor loop is allowed and it performs better (respectively). If your are working with a cell or matrix of some kind and your nested loops cover a connected portion of it, you can always use the linear index approach. For example

n=100;
s=0;
a=randi([1 n],n);
for i=1:n
   for j=1:n
       s=s+a(i,j);
   end
end

can be rewritten as

n=100;
s=0;
a=randi([1 n],n);
for i=1:n^2
    s=s+a(i);
end

But again if your array is large and your iterations do not depend on each other, it's usually better to take advantage of the 'parfor' construct.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top