MATLAB: How to perform row wise operation for a matrix of 350×350

row wise operations

Hi, I have a matrix of 350×350 all zeros and ones. Now i have to go through each row and assign 40 to all 1s in the first line until i hit a 0, then i have to go to the second row and assign 40 to all 1s until i hit zero and i have to repeat this until the n-th line is 0 and i have to continue the same concept for the remaining numbers i.e now i have to again start with first row but this time from the place where i have left it last time i.e. the number(1) after zero should replace with some random number other than 40 and i have to continue the same concept for 350×350 matrix
for example if A=[1 0 1 0 1; 1 0 1 0 1;1 0 0 0 0; 0 0 0 1 1;1 1 0 0 0] it should change to A=[40 0 50 0 60; 40 0 50 0 60; 40 0 0 0 0 ;0 0 0 70 70; 80 80 0 0 0];
From the code below i could be able to change the values for initial rows but i have no idea how to proceed further so, can anyone help me with this and the code below is only working if the row starts with 1 but i have some rows where it is starting with 0s (if the row is starting with 0 it should be neglected)
for i = 1:size(A, 1)
ind = find(A(i, :) == 0);
if isempty(ind)
ind2 = size(A, 2);
else
ind2 = ind(1) - 1;
end
A(i, 1:ind2) = 40;
End
Thanks in advance Agastya

Best Answer

The following would work:
for row = 1:size(A, 1)
pos0 = [0 find([A(row, :) 0] == 0]; %make sure that beginning and end are included
for idx = 1:numel(pos0)-1
A(row, pos0(idx)+1 : pos0(idx+1)-1) = 30 + 10*idx;
end
end