How to replace unique interval of columns in each row of a matrix with zero?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Michael König
el 4 de Jul. de 2022
Comentada: Michael König
el 4 de Jul. de 2022
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
1 comentario
Respuesta aceptada
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]
idx_column = [5
1
3]
A2 = A1 .* ((1:size(A1,2))>idx_column)
0 comentarios
Más respuestas (2)
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
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.
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
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.
Ver también
Categorías
Más información sobre Logical 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!