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

3 次查看(过去 30 天)
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.

采纳的回答

Hikaru
Hikaru 2015-2-23
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 个评论
Stephen23
Stephen23 2015-2-23
编辑:Stephen23 2015-2-23
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 2015-2-24
编辑:Hikaru 2015-2-24
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by