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

조회 수: 3 (최근 30일)
Suman
Suman 2015년 2월 23일
편집: Hikaru 2015년 2월 24일
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