Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

How to optimize this loop

1 visualización (últimos 30 días)
Israel Campiotti
Israel Campiotti el 16 de Ag. de 2017
Cerrada: MATLAB Answer Bot el 20 de Ag. de 2021
I want to do a loop like this
for i = 1:n
A(i,B(i,1)) = 1;
end
but my matrix has size one million. Is there a way to do it faster?

Respuestas (2)

Michelangelo Ricciulli
Michelangelo Ricciulli el 16 de Ag. de 2017
I think that this should save some time, since it avoids the for-loop:
i = 1:n;
A(i,B(i,1)) = 1;
  1 comentario
Image Analyst
Image Analyst el 16 de Ag. de 2017
In my testing that brought it from 0.01 seconds to 24 minutes.

Image Analyst
Image Analyst el 16 de Ag. de 2017
On my computer, it takes only 9 milliseconds for a million elements:
rows = 1000000;
columns = 5;
A = rand(rows, columns);
B = randi(columns, rows, 1);
tic
for k = 1 : rows
A(k, B(k)) = 1;
end
toc
Why do you need it faster?
  1 comentario
Israel Campiotti
Israel Campiotti el 16 de Ag. de 2017
Mine is taking more than 20minutes

La pregunta está cerrada.

Community Treasure Hunt

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

Start Hunting!

Translated by