How to replace data in a matrix by comparing from another matrix?

4 ビュー (過去 30 日間)
suchismita
suchismita 2015 年 5 月 5 日
コメント済み: suchismita 2015 年 5 月 5 日
I have a matrix A,
[1 5
2 6
3 6
4 7
5 6]
and I have another matrix B as
[1 2
1 3
1 4
1 5
2 3
2 4
3 4
3 5
4 5]
now i want to compare B with a and i want to replace 2nd column of B with A data for example,
[1 5
1 5
1 5
1 5
2 6
2 6
3 6
3 6
4 7]
in first column when there is 1 it will take the value of matrix A's second column data as 5 and when first column is having 2 it will take the value of 2 from matrix A.
please please help me.

採用された回答

David Sanchez
David Sanchez 2015 年 5 月 5 日
for k=1:length(B)
x = A(:,1)==B(k,1);
B(k,2) = A(x,2);
end
B =
1 5
1 5
1 5
1 5
2 6
2 6
3 6
3 6
4 7
  2 件のコメント
suchismita
suchismita 2015 年 5 月 5 日
thank u so much....
Stephen23
Stephen23 2015 年 5 月 5 日
Andrei Bobrov's solution is much neater.

サインインしてコメントする。

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2015 年 5 月 5 日
編集済み: Andrei Bobrov 2015 年 5 月 5 日
[lo,ii] = ismember(B(:,1),A(:,1));
out = B;
out(lo,2) = A(ii(lo),2);
  3 件のコメント
Andrei Bobrov
Andrei Bobrov 2015 年 5 月 5 日
Hi Stephen! I corrected..
suchismita
suchismita 2015 年 5 月 5 日
thank u so much.....

サインインしてコメントする。


Nobel Mondal
Nobel Mondal 2015 年 5 月 5 日
Assuming, the 'a' matrix has unique values in the first column
for bRow= 1:size(b, 1)
aRow = find(a(:,1)==b(bRow,1), 1);
if ~isempty(aRow)
b(thisrow,2) = a(aRow,2);
end
end

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by