Borrar filtros
Borrar filtros

How to vectorize this code with logical idexing

1 visualización (últimos 30 días)
pietro
pietro el 14 de Mayo de 2014
Comentada: pietro el 15 de Mayo de 2014
Hi all,
I have the following code, how can I avoid the for to make it faster?
a=[10:5:50];
b=[10:20:50];
c=rand(size(a));
for i=length(b)-1
d=c(a>=b(i) & a<b(i+1));
end
thanks
cheers
  1 comentario
Jos (10584)
Jos (10584) el 15 de Mayo de 2014
Since you're only storing the last values of d in each iteration, you can skip the for-loop completely:
i = length(b)-1
d = c(a>=b(i)) & a<b(i+1))
but I am pretty sure you intend to do something else.
What should happen with the values of d obtained in the iterations 1 to length(b)-2?

Iniciar sesión para comentar.

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 14 de Mayo de 2014
Editada: Andrei Bobrov el 15 de Mayo de 2014
a=[10:5:50];
b=[10:20:50];
c=rand(size(a));
[~,ii] = histc(a,b);
d = accumarray(ii(:),c(:),size(b(:)),@(x){x})
  3 comentarios
Andrei Bobrov
Andrei Bobrov el 15 de Mayo de 2014
corrected
pietro
pietro el 15 de Mayo de 2014
It works. Thanks

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by