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

 Respuesta aceptada

Guillaume
Guillaume el 21 de Nov. de 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 comentarios

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.
True.

Iniciar sesión para comentar.

Más respuestas (3)

A(logical(cumprod(A,2)))=40

2 comentarios

Very elegant.
Hi Azzi Abdelmalek,
Can you explain me this logic?

Iniciar sesión para comentar.

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 comentarios

This does not work if the row no 0's.
Agastya
Agastya el 21 de Nov. de 2014
Editada: Agastya el 21 de Nov. de 2014
Thank you for your response

Iniciar sesión para comentar.

Thorsten
Thorsten el 21 de Nov. de 2014
Editada: Thorsten el 21 de Nov. de 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 comentarios

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.

Iniciar sesión para comentar.

Categorías

Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.

Preguntada:

el 21 de Nov. de 2014

Comentada:

el 24 de Nov. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by