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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by