How to replace unique interval of columns in each row of a matrix with zero?

1 visualización (últimos 30 días)
I have a matrix consisting of ones and zeros and have to replace the entries of each row up to a unique column number for each row with a zero. A for-loop is not acceptable.
Exaple:
A1= [1 1 1 1 1 1 1 0 0 1 1 0 0 1
1 1 1 1 1 1 1 1 0 1 1 0 0 1
1 1 1 1 1 1 1 0 1 1 1 1 1 0]
idx_column = [5
1
3]
A2= [0 0 0 0 0 1 1 0 0 1 1 0 0 1
0 1 1 1 1 1 1 1 0 1 1 0 0 1
0 0 0 1 1 1 1 0 1 1 1 1 1 0]
I tried the following without success:
A2 = A1;
A2(:,[1;1;1]:[5;1;3]) = 0;
Is there a possibility to replace a unique interval in each row of a matrix efficiently? A for loop is not acceptable.
Thank you very much!
Best regards,
Michael

Respuesta aceptada

Bruno Luong
Bruno Luong el 4 de Jul. de 2022
A1= [1 1 1 1 1 1 1 0 0 1 1 0 0 1
1 1 1 1 1 1 1 1 0 1 1 0 0 1
1 1 1 1 1 1 1 0 1 1 1 1 1 0]
A1 = 3×14
1 1 1 1 1 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 0 1 1 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 0
idx_column = [5
1
3]
idx_column = 3×1
5 1 3
A2 = A1 .* ((1:size(A1,2))>idx_column)
A2 = 3×14
0 0 0 0 0 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 1 1 1 0

Más respuestas (2)

Abderrahim. B
Abderrahim. B el 4 de Jul. de 2022
Editada: Abderrahim. B el 4 de Jul. de 2022
Not a smart way but still do the job:
A1 = [1 1 1 1 1 1 1 0 0 1 1 0 0 1
1 1 1 1 1 1 1 1 0 1 1 0 0 1
1 1 1 1 1 1 1 0 1 1 1 1 1 0] ;
A2 = A1 ;
A2(1, 1:5) = 0; A2(2, 1) = 0; A2(3, 1:3) = 0;
A2
A2 = 3×14
0 0 0 0 0 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 1 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 1 1 1 1 0
In case you have a huge matrix and you want replace multiple elements, use for loop if you see that it is not fast try parfor. Note that parfor requires to have Parallel Computing Toolbox license.
  1 comentario
Michael König
Michael König el 4 de Jul. de 2022
Thank you for your answer. I will check whether a simple for loop is actually faster - but the method of your solution is very helpful for different kinds of problems in any way.

Iniciar sesión para comentar.


David Hill
David Hill el 4 de Jul. de 2022
Why is a for-loop not acceptable?
for k=1:length(idx_column)
A1(k,1:idx_column(k))=0;
end
  2 comentarios
Michael König
Michael König el 4 de Jul. de 2022
I have huge matrices and am searching for a more efficient method in order to reduce computing times. Is there a more direct way?
I found https://de.mathworks.com/matlabcentral/answers/164993-how-to-use-a-vector-as-indices-for-matrix - but in my problem there can be multiple rows with a number, so that solution is not fitting for me.
Bruno Luong
Bruno Luong el 4 de Jul. de 2022
Editada: Bruno Luong el 4 de Jul. de 2022
For-loop is the most straighforward and possible the fastest method.

Iniciar sesión para comentar.

Categorías

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

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by