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

5 views (last 30 days)
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

Guillaume
Guillaume on 21 Nov 2014
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
Guillaume
Guillaume on 21 Nov 2014
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)

Azzi Abdelmalek
Azzi Abdelmalek on 21 Nov 2014
A(logical(cumprod(A,2)))=40

Azzi Abdelmalek
Azzi Abdelmalek on 21 Nov 2014
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

Thorsten
Thorsten on 21 Nov 2014
Edited: Thorsten on 21 Nov 2014
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
Agastya
Agastya on 21 Nov 2014
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?
Guillaume
Guillaume on 21 Nov 2014
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.

Community Treasure Hunt

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

Start Hunting!