Array matching

I have 2 arrays that i'd like to compare values and create a child that contains matching values (and I'd like to do this the fastest way possible).
Example:
A = [1;0;-1;0;0;0;1]
B = [0;1;-1;0;1;0;1]
child = [0;0;-1;0;0;0;1]
Your help is greatly appreciated! Thank you.

回答 (1 件)

Geoff
Geoff 2012 年 4 月 26 日

4 投票

child = A;
child(A ~= B) = 0;

9 件のコメント

Richard Brown
Richard Brown 2012 年 4 月 26 日
pah! pathetic! None of this two line nonsense!
child = A .* (A == B)
Jan
Jan 2012 年 4 月 26 日
Even an incorrect answer would not be "nonsense".
I assume Geoff's solution is faster than Richard's, because it does not need the implicit conversion of the logical array "(A==B)" to a double and perform LENGTH(A) floating point multiplications.
James Tursa
James Tursa 2012 年 4 月 26 日
child = A .* (A == B) will produce NaN values instead of the desired 0 if the A element is inf and the B element is not inf.
Geoff
Geoff 2012 年 4 月 29 日
Erm, thanks Richard. I'm a computer scientist, not a mathematician.
Richard Brown
Richard Brown 2012 年 4 月 30 日
I'm guessing from these responses that I should probably point out that I was joking ... :)
If I had thought my solution was better, I would have posted it as a separate answer
James Tursa
James Tursa 2012 年 4 月 30 日
Maybe some regulars might have recognized this, but it is likely newbies would not. Hence my comment.
Richard Brown
Richard Brown 2012 年 4 月 30 日
Fair point. The same might also be true of
non-native English speakers who may have
thought I was being genuinely critical of
dear Geoff :-)
Geoff
Geoff 2012 年 5 月 2 日
Hey it even fooled me... I was under a bit of pressure and lost my sense of humour for a couple of days. =)
Jan
Jan 2012 年 5 月 2 日
I frequently confuse humor and humerus. Therefore I thank you for your clarifications.
Is the OP still interested in the solution?

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

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

質問済み:

2012 年 4 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by