フィルターのクリア

how to find common values in two matrix for particular column?

1 回表示 (過去 30 日間)
Shubham Mohan Tatpalliwar
Shubham Mohan Tatpalliwar 2018 年 10 月 24 日
編集済み: Bruno Luong 2018 年 10 月 25 日
if true
% code
A=[0 1 1 0; 1 0 0 1; 1 1 0 0; 0 0 1 1]
B=[0 1 0 1; 1 0 1 0; 0 0 1 1; 1 1 0 0]
end
for 1st column of A and ALL columns of b
if we check
the expected answer is
1 0 2 1
these are the total number of instances they are matching
  3 件のコメント
Bruno Luong
Bruno Luong 2018 年 10 月 24 日
Please put care on
  • code formatting
  • explanation
  • formulation of synthetic question (Why give the whole A and ask just result that depends only on first column)
Shubham Mohan Tatpalliwar
Shubham Mohan Tatpalliwar 2018 年 10 月 24 日
in the first column of A, there are two ones at 2nd row and 3 rd row
so considering this it will check all columns of B
in the first column of B, there is 1 in 2nd row that match and it did not match with the 3rd row
so for 1st column of B answer is 1
for 2nd column of B and 1st column of A nothing match so the answer is zero
Further for the 3rd column of B and 1st column A the second and 3rd row of both are 1 so the answer is 2
and so on...

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

採用された回答

Bruno Luong
Bruno Luong 2018 年 10 月 24 日
>> sum(A(:,1)+B==2)
ans =
1 0 2 1
>>
  9 件のコメント
Shubham Mohan Tatpalliwar
Shubham Mohan Tatpalliwar 2018 年 10 月 25 日
can u explain a bit about this code?
Bruno Luong
Bruno Luong 2018 年 10 月 25 日
編集済み: Bruno Luong 2018 年 10 月 25 日
The reshape() just moves the 2nd dimension (column) of A to the 3rd dimension
So each origin column A(:,j) now can be addressed as A(:,:j).
The explanation for SUM(... & B) you already know, but now use in the context of auto-expansion. Excepted that the result now is of the size (1 x size(B,2) x size(A,2)): each number of common 1-values of B and A(:,j) is in a slide XX(1,:,j) before SQUEEZE is invoked.
The squeeze command removes the 1st singleton dimension, so XX(:,j) is common 1-values of B and A(:,j).
NOTE: You might transpose the result so each row corresponds to result of a column of A with you prefer.

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

その他の回答 (1 件)

Stephen23
Stephen23 2018 年 10 月 24 日
You don't need to use a loop:
>> sum(permute(A,[3,2,1])&permute(B,[2,3,1]),3)
ans =
1 0 1 2
0 1 2 1
2 1 0 1
1 2 1 0

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by