How to perform row wise operation for a matrix of 250x250

Hi, I have a matrix of 250x250 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, which characterizes the end of the grain. Can anyone let me know the basic idea of coding for the above concept, For an example 5x5 matrix,A=[1 1 1 0 1; 1 1 0 1 1; 1 1 1 0 1; 1 1 0 0 1; 1 1 0 1 0]
Thanks in advance Agastya

 Accepted Answer

A simple way of doing this is to use a for to loop over each row and use find on each of these rows to find the column of the first 0. You then assign 40 to all columns of the row less than this first column.

3 Comments

This does not work if the row no 0's.
Agastya asked for the basic idea of coding. That's what I've presented. It can of course be refined to cope with cases of all 0s or all 1s.

Sign in to comment.

More Answers (3)

A=[1 1 1 0 1; 1 1 0 1 1; 1 1 1 0 1; 1 1 0 0 1; 1 1 0 1 0]
for k=1:size(A,2)
idx=strfind(A(k,:),[1 0]);
A(k,1:idx)=40;
end

2 Comments

This does not work if the row no 0's.
Thank you for your response

Sign in to comment.

This is basically the algorithm suggested by Guillaume with an addditional check for the special case where the row has no 0's; note that this only works if a row always starts with a 1.
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

4 Comments

Hi Throsten,
This is helpful but there are some lines starting with zeros how to deal with those cases?? And what is the initial code to read that text file?
Well, test if the index is 1 and if it is don't replace anything.
As for reading that (?) text file, start a new question. You've never mentioned a text file and it has nothing to do with your initial question.
Hi Guillaume,
sorry for that, but my questions is i have that matrix 250x250 in a text file,so how to read that text file?
As I said, start a new question. You'll get more chance of an answer as people won't usually look at questions that have been marked as answered.

Sign in to comment.

Categories

Asked:

on 21 Nov 2014

Commented:

on 24 Nov 2014

Community Treasure Hunt

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

Start Hunting!