Replacing elements of a Matrix meeting conditional

Hi, I have two matrixes and wish to replace the first column of matrix A, with elements of the fourth column of matrix B, but just in the case the elements of the first columns of A and B are equal.
I tried the following, but its probably not correct. Can someone help me out?
for j=1:size(A,1)
if A(j,1)==B(:,1);
A(j,1)=B(:,4);
end
end

 採用された回答

Fangjun Jiang
Fangjun Jiang 2011 年 8 月 6 日

0 投票

A=rand(14,5);A(:,1)=1:14;
B=rand(5,4);B(:,1)=10:-2:2;B(:,4)=10*B(:,1);
[Dummy,IndexA,IndexB]=intersect(A(:,1),B(:,1));
A(IndexA,1)=B(IndexB,4)

4 件のコメント

Patricia
Patricia 2011 年 8 月 6 日
Thanks. But still not working. My problem is that the "matching" element of matrix B, doesn´t necessarily is on the same line as the element of matrix A.
Fangjun Jiang
Fangjun Jiang 2011 年 8 月 6 日
Paulo's answer will do it. Don't accept an answer before the problem is solved. Providing an example data will always help.
Patricia
Patricia 2011 年 8 月 7 日
Ja, first time using this 'answers'... I'm still on it. The arrays are A (1401X5) and B (137X4). The values on first column variate from 1 to 1400; in 1 step size for A, and randomly for B.
Patricia
Patricia 2011 年 8 月 7 日
'randomly' but still between 1 and 1400

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

その他の回答 (2 件)

Paulo Silva
Paulo Silva 2011 年 8 月 6 日

0 投票

%sample arrays
a=randi([1 6],4,4);
b=randi([1 6],4,4);
e=a(:,1)==b(:,1); %find what elements are equal in first columns
a(e,1)=b(e,4) %replace the elements

1 件のコメント

Patricia
Patricia 2011 年 8 月 7 日
'eq' won´t work if the matrixes have <> size

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

Patricia
Patricia 2011 年 8 月 7 日

0 投票

Just worked it out! I had a similar problem once... had forgotten :) Used:
idx=ismember(A:,1), B(:,1)); B = [B A(idx,4)];
so I added a column in B, which is also OK. Thanks again!

1 件のコメント

Fangjun Jiang
Fangjun Jiang 2011 年 8 月 7 日
Nice! I also updated my answer. It's similar, for your reference.

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

カテゴリ

ヘルプ センター および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by