I need to replace an enitre row, if any of the value goes less than zero

2 visualizaciones (últimos 30 días)
I need to check each row, whether is there any of the value less than zero in a particular row. If any value in a row is less than zero, i have to replace the entire row itself.
For example,
a1=[1 2; 3 4; -5 6] a2=[22 23; 56 78; 89 75]
Step 1: I need to check whether any element of a row is less than zero in matrix a1...... Step 2: If there is any negative value, i have to replace that particular row by the the same row of the another matrix a2.
Problem with the coding I did, If there is only one negative value in a row, then the negative value only is replaced by the another matrix of the same (row,column), but I couldn't replace the entire row.

Respuesta aceptada

Hikaru
Hikaru el 23 de Feb. de 2015
This will solve it.
a1=[1 2; 3 4; -5 6]
a2=[22 23; 56 78; 89 75]
neg = a1<0 % return '1' for values less than zero
a1(neg,:) = a2(neg,:) % step 2
  4 comentarios
Stephen23
Stephen23 el 23 de Feb. de 2015
Editada: Stephen23 el 23 de Feb. de 2015
Are both of X and X_previous really the same size? Use the size command and tell us exactly what their sizes are.
This error arises because negative is referring to positions in one of the matrices that do not exist. Because negative is calculated from X, it is likely that X_previous is smaller than X, thus giving this error.
Hikaru
Hikaru el 24 de Feb. de 2015
Editada: Hikaru el 24 de Feb. de 2015
Now that I redo this problem with another matrix, the solution above does not work if the negative value is located in the second column.
Assuming you have matrix of 2 columns only, you might want to try the code below:
neg1 = a1(:,1)<0
neg2 = a1(:,2)<0
neg = neg1|neg2
a1(neg,:) = a2(neg,:)
I haven't fully tested it, but it should give you a start. Like Stephen said, you need to be more specific for a more specific solution.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by