Repeat rows that start with a particular value

Hi, I am trying to repeat a column in an array where all columns start with 1. Example, I want row 2 (1110100) to be repeated in rows where the second column contain 1. So this would apply to the first and last row.
0 1 0 0 0 0 0
1 1 1 0 1 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 1 0 0 0 0 0
which I want to look like this
1 1 1 0 1 0 0
1 1 1 0 1 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
1 1 1 0 1 0 0

 Respuesta aceptada

Image Analyst
Image Analyst el 7 de Jun. de 2016
Try this to find the rows that need repeating:
m = [...
0 1 0 0 0 0 0
1 1 1 0 1 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 1 0 0 0 0 0]
rowsToRepeat = m(:, 2) == 1
We can't fully answer the question because you did not say where you want the repeated rows to go. Do you want to append them to the end? Do you want the repeated row to go right below it's original location?

5 comentarios

Andre Munoz
Andre Munoz el 7 de Jun. de 2016
Thanks for the reply. Please see that I have updated the original question for you to answer.
You should learn about repmat(). Here's one way:
m = [...
0 1 0 0 0 0 0
1 1 1 0 1 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 1 0 0 0 0 0]
[rows, columns] = size(m);
rowsToRepeat = m(:, 2) == 1
allRow2 = repmat(m(2,:), [rows, 1])
m(rowsToRepeat, :) = allRow2(rowsToRepeat,:)
Here is another way:
rowsToRepeat = m(:, 2) == 1
m(rowsToRepeat, :) = repmat(m(2,:), [sum(rowsToRepeat), 1])
Andre Munoz
Andre Munoz el 8 de Jun. de 2016
This has worked. Thank you very much.
Andre Munoz
Andre Munoz el 8 de Jun. de 2016
Please can you help me again. Now I want to take the top row (0100000) and repeat this where there are zeros in the first column. I have tried my self but this does not work for me. Thanks
Andre Munoz
Andre Munoz el 8 de Jun. de 2016
Don't worry, I now have it working thanks.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre MATLAB en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 7 de Jun. de 2016

Comentada:

el 8 de Jun. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by