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

1 view (last 30 days)
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

Accepted Answer

Bruno Luong
Bruno Luong on 4 Jul 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

More Answers (2)

Issa
Issa on 4 Jul 2022
Edited: Issa on 4 Jul 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 Comment
Michael König
Michael König on 4 Jul 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.

Sign in to comment.


David Hill
David Hill on 4 Jul 2022
Why is a for-loop not acceptable?
for k=1:length(idx_column)
A1(k,1:idx_column(k))=0;
end
  2 Comments

Sign in to comment.

Categories

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by