Is it possible to vectorize this ?

1 visualización (últimos 30 días)
Omar Ali Muhammed
Omar Ali Muhammed el 26 de Abr. de 2021
Editada: Matt J el 26 de Abr. de 2021
A matrix A(100x1000) a selective column defined in B(1x1000). The required processing is the mean of non zero elements of each column of A referenced by B. Without the use of loops.
Regards

Respuesta aceptada

Matt J
Matt J el 26 de Abr. de 2021
Editada: Matt J el 26 de Abr. de 2021
A(~A)=nan;
result=mean(A(:,B),1,'omitnan')
  2 comentarios
Omar Ali Muhammed
Omar Ali Muhammed el 26 de Abr. de 2021
Dear, it is wonderful.
How can we 'omitnan' if we replace mean by trimmean?
Matt J
Matt J el 26 de Abr. de 2021
Editada: Matt J el 26 de Abr. de 2021
Dear, it is wonderful.
I'm very glad. Please Accept-click the answer to indicate so.
How can we 'omitnan' if we replace mean by trimmean?
What would you be excluding?Zeros again? If so,
A(~A)=inf;

Iniciar sesión para comentar.

Más respuestas (1)

Jan
Jan el 26 de Abr. de 2021
AB = A(:, B);
result = sum(AB, 1) ./ sum(AB ~= 0, 1);
mean('omitnan') replaces the NaNs by zeros for the summation and calculates the number of non-NaNs by sum(~isnan(AB)). Therefore this code should be faster, because it avoids replacing zeros by NaNs and back to zeros again.
  1 comentario
Matt J
Matt J el 26 de Abr. de 2021
Editada: Matt J el 26 de Abr. de 2021
because it avoids replacing zeros by NaNs and back to zeros again.
+1. Although, I would argue, they probably should have been NaNs instead of zeros from the very beginning.

Iniciar sesión para comentar.

Categorías

Más información sobre Mathematics en Help Center y File Exchange.

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by