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

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

Accepted Answer

Hikaru on 23 Feb 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
Hikaru on 24 Feb 2015
Edited: Hikaru on 24 Feb 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.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by