
indexing into a matrix to eliminate a loop
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Joao Ejarque
el 10 de En. de 2014
Comentada: Joao Ejarque
el 19 de En. de 2014
This file generates an ergodic density matrix. I would like to get rid of the inner loop (over ii). The first line in the outer loop - F1 = F0*P; - reshuffles columns of F0 to create F1, and it is as quick as it can get.
But depending on how the GPOL matrix looks like, the inner loop can be quite slow. Now this line of command (which I think was courtesy of Matt J,
Zi(sub2ind(size(Zi),GPOL(ii,:),1:numel(GPOL(ii,:))))=F1(ii,:);
this is already pretty smart. It is reshuffling the rows of F1, one by one. here you can look at the entire code, and i will state the question below (you may be guessing it already)
function[F2,ijj,differ] = densityiter(F0,GPOL,P);
[nh ny]=size(F0);
niter = 400;
for ijj=1:niter
F1 = F0*P;
Z0 = 0*ones(nh,ny);
F2 = 0*ones(nh,ny);
for ii=1:nh
Zi = Z0;
Zi(sub2ind(size(Zi),GPOL(ii,:),1:numel(GPOL(ii,:))))=F1(ii,:);
F2 = F2 + Zi;
end
differ = sum(sum(abs(F2-F0)));
F0=F2;
if differ<0.000001;break,else,end
end
The question then is: does anyone know how to replace the loop over ii to get the same effect only faster? to work on all rows of F1 at the same time? this is the piece
for ii=1:nh
Zi = Z0;
Zi(sub2ind(size(Zi),GPOL(ii,:),1:numel(GPOL(ii,:))))=F1(ii,:);
F2 = F2 + Zi;
end
thank you. i hope this rephrasing on the problem helps.
2 comentarios
Matt J
el 10 de En. de 2014
We can talk about it, but please highlight your code and apply the

formatting button first.
Respuesta aceptada
Más respuestas (1)
Amit
el 17 de En. de 2014
I am assuming that GPOL and F1 are of same size. Then instead of:
for ii=1:nh
Zi = Z0;
Zi(sub2ind(size(Zi),GPOL(ii,:),1:numel(GPOL(ii,:))))=F1(ii,:);
F2 = F2 + Zi;
end
you can so something like this:
Zi = Z0;
[m n] = size(GPOL);
F1tmp = F1';
Zi(sub2ind(size(Zi),reshape(GPOL',1,m*n),repmat(1:numel(GPOL(1,:)),1,nh))) = F1tmp(1:m*n);
This might need some tweaking. If you post a sample data then I can verify this.
2 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!