MATLAB: Logical operation on column of a matrix

matrix manipulation

I'm dealing with a larger problem but say I have a 5×6 matrix: A=[0 0 0 0 1 0;0 0 0 1 0 0;1 0 0 0 0 1;0 0 1 1 1 1 ;0 1 0 1 1 0]
My goal is to complete the matrix such that for each column, as soon as 1 is present, then this will be 1 until the last row.
Typically:
Result=[0 0 0 0 1 0;0 0 0 1 1 0;1 0 0 1 1 1;1 0 1 1 1 1;1 1 1 1 1 1] Any clue ? I can find the index on columns no problem, but i dont know how to move forward then

Best Answer

Here are a few methods to try:
>> A = [0,0,0,0,1,0;0,0,0,1,0,0;1,0,0,0,0,1;0,0,1,1,1,1;0,1,0,1,1,0]
A =
0 0 0 0 1 0
0 0 0 1 0 0
1 0 0 0 0 1
0 0 1 1 1 1
0 1 0 1 1 0
>> B = +(cumsum(A,1)>0)
B =
0 0 0 0 1 0
0 0 0 1 1 0
1 0 0 1 1 1
1 0 1 1 1 1
1 1 1 1 1 1
>> B = sign(cumsum(A,1))
B =
0 0 0 0 1 0
0 0 0 1 1 0
1 0 0 1 1 1
1 0 1 1 1 1
1 1 1 1 1 1
>> B = +~~cumsum(A,1)
B =
0 0 0 0 1 0
0 0 0 1 1 0
1 0 0 1 1 1
1 0 1 1 1 1
1 1 1 1 1 1