Compare two arrays based on indexes

Hello,
Please help me with the following:
consider two arrays
A=[19;20;19;20;21;22]; B=[1;1;4;4;4;4];
A user should provide two values, i.e. v1, v2.
A condition (maybe with logical if) should search if v1 belong to A and v2 belong to B.
if those values both belong to A and B, another operation should take place, for example C=100 or C=200;
For example,
If v1=19; && v2=2;
Those values do not belong both in A and B, so C=200
If v1=19; && v2=1;
Those values belong both in A and B, so C=100
The indexes of v1 and v2 in A and B should be the same in order for C=100;
That means that the operation C=100; would take place only in the following combinations:
v1=19; v2=1;
v1=20; v2=1;
v1=19; v2=4;
v1=20; v2=4;
v1=21; v2=4;
v1=22; v2=4;
The condition
If v1=21; && v2=1; theoritically gives C=100;
but the indexes of v1 and v2 in A and B are not equal (5th index in A for v1 and 1st,2nd indexes for v2 in B).
Than you very much,
Best,
Pavlos

回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2017 年 7 月 14 日
編集済み: Andrei Bobrov 2017 年 7 月 14 日

1 投票

M = [A,B];
V = [v1,v2];
C = [200,100];
out = C(ismember(V,M,'rows')+1);

4 件のコメント

pavlos
pavlos 2017 年 7 月 14 日
Thank you, but how v1 and v2 are taken into account?
Andrei Bobrov
Andrei Bobrov 2017 年 7 月 14 日
I'm fixed.
pavlos
pavlos 2017 年 7 月 14 日
Thank you again, but your code does not consider the equalities of the indexes of v1 and v2 in A and B.
In order for C=100; v1 and v2 should only belong to A and B but also, refer to the same index in A and B.
For instance, v1=19 and v2=1 gives C=100 because the index of v1 in A is 1 and the index of v2 in B is also 1.
Guillaume
Guillaume 2017 年 7 月 14 日
編集済み: Guillaume 2017 年 7 月 14 日
your code does not consider the equalities of the indexes
Yes, it does. That's exactly how ismember with the 'rows' option work. Try it with V = [22, 1] and see that it returns 200.
Andrei's answer is the most efficient way to do exactly what you asked.

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

カテゴリ

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

質問済み:

2017 年 7 月 14 日

編集済み:

2017 年 7 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by