matching from multiple arrays

7 ビュー (過去 30 日間)
Tooba Sheikh
Tooba Sheikh 2019 年 1 月 21 日
コメント済み: madhan ravi 2019 年 1 月 21 日
I have an array,
ref = [1 1 0 0 1],
and 3 more arrays
a{1}=[1 0 0 0 1]
a{2}=[1 0 0 0 0]
a{3}=[0 0 1 0 1]
I want to produce an array by comparing ref to all others, such that: if an element in position i in ref matches the element in position i in any of the a{} then it is considered a match otherwise not. In case of a match (ref=1, a=1,0,0), we keep the value of ref (ans=1), otherwise (ref=1, a=0,0,0) the value is flipped (ans=0).
So based on this condition, the output for this example will be
ans=[1 0 0 0 1]
It can easily be done using for loops,
for i=1:5
match=0;
for j=1:3
if(ref(i) == a{j}(i))
ans(i)=ref(i);
match=1;
continue;
end
end
if(~match)
ans(i)=1-ref(i);
match=1;
end
end
but is there a more efficient way to do this?

採用された回答

madhan ravi
madhan ravi 2019 年 1 月 21 日
編集済み: madhan ravi 2019 年 1 月 21 日
A=vertcat(a{:});
Result= 1*(any(A) & ref)
  2 件のコメント
Stephen23
Stephen23 2019 年 1 月 21 日
+1 Neat idea. Could also be on one line:
>> +(any(vertcat(a{:}))&ref)
ans =
1 0 0 0 1
madhan ravi
madhan ravi 2019 年 1 月 21 日
Thank you Stephen!

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

その他の回答 (1 件)

Birdman
Birdman 2019 年 1 月 21 日
One way:
Result=double(ref & (ref==a{1} | ref==a{2} | ref==a{3}))

カテゴリ

Help Center および File ExchangeIntroduction to Installation and Licensing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by