필터 지우기
필터 지우기

How to match elements of matrix having different dimensions?

조회 수: 1 (최근 30일)
Megha
Megha 2018년 11월 5일
댓글: Guillaume 2018년 11월 6일
if true
% code
endI have some dates in say variable A as 10x6 double form :
2000 01 01 00 00 01
2000 01 01 00 00 02
2000 01 01 00 00 03
...
...
...
2000 01 01 00 00 09
2000 01 01 00 00 10
Now another matrix B as 5x6 double form :
2000 01 01 00 00 01
2000 01 01 00 00 02
2000 01 01 00 00 03
2000 01 01 00 00 09
2000 01 01 00 00 10
Now i would like to find the row index of A where elements of B are found. i.e. answer = row index: 1,2,3,9,10.
I tried
idx = ismember(A, B,'rows'); % it does not work!
so i tried,
idx = ismember(B, A,'rows'); % which also does not work!
So i used conventional hour-taking method:
% tic
% idx = nan(length(A),1);
% for i = 1:A
% for j = 1:B
% if isequal(A(i,:), B(j,:))
% idx(i,1) = j;
% end
% end
% end
% toc
Any short-cut to solve this...?

채택된 답변

Guillaume
Guillaume 2018년 11월 5일
find the row index of A where elements of B are found
ismember is indeed the function for that, so you will have to explain why it does not work. In this particular case:
isinB = ismember(A, B, 'rows');
Note that I've changed the name of the return variable to something more accurate than idx since the first output of ismember is not indices but a logical vector indicating whether the corresponding row of A is found in B. If you do want indices:
idx = find(isinB);
However, more often than not, it is easier to work with the logical vector and find is just a waste of time.
  댓글 수: 2
madhan ravi
madhan ravi 2018년 11월 5일
idx = find(isinB) %remove semicolon it gives the exact answer you want
Guillaume
Guillaume 2018년 11월 6일
I have no answer! if i know why it doesnt work, whats the point of posting it here!
"It doesn't work" is a useless statement on its own. In what does it not work? Do you get an error message? If so, what is the error message? Do you get a different result than what you expected? If so, what do you get and what did you expect?
As I said, ismember is the function required and it gives the correct result. So if it doesn't work for you, we need to undersand why.
>> a = datevec(datetime(2000,1,1,0,0,0) + seconds(1:10)')
a =
2000 1 1 0 0 1
2000 1 1 0 0 2
2000 1 1 0 0 3
2000 1 1 0 0 4
2000 1 1 0 0 5
2000 1 1 0 0 6
2000 1 1 0 0 7
2000 1 1 0 0 8
2000 1 1 0 0 9
2000 1 1 0 0 10
>> b = datevec(datetime(2000,1,1,0,0,0) + seconds([1; 2; 3; 9; 10]))
b =
2000 1 1 0 0 1
2000 1 1 0 0 2
2000 1 1 0 0 3
2000 1 1 0 0 9
2000 1 1 0 0 10
>> idx = find(ismember(a, b, 'rows'))
idx =
1
2
3
9
10
As you can see it produces the exact output you asked for.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by