필터 지우기
필터 지우기

How to compare two vectors and output the index?

조회 수: 11 (최근 30일)
Aswin Sandirakumaran
Aswin Sandirakumaran 2018년 4월 26일
댓글: Aswin Sandirakumaran 2018년 4월 26일
For eg:
A = [60,600,15]
B = [60,512,30,13]
Now, take B(1) (60 here) and compare it with A(1)(60 here) If 60<=60 print index of A(i) ==> O/P should be 1. then increase A(i) += 1 so now B(1) should compare if it is <= A(2) 60<=512 yes true! so o/p = 2. It should compare all elements less than or equal to itself and output its index in a new vector.
Final output should be like this:
B(1) = [1,2];
B(2) = [2];
B(3) = [1,2];
B(4) = [1,2,3].

채택된 답변

Stephen23
Stephen23 2018년 4월 26일
편집: Stephen23 2018년 4월 26일
This is easy in just two lines using find and accumarray:
>> A = [60,600,15];
>> B = [60,512,30,13];
>> [R,C] = find(bsxfun(@le,B(:),A));
>> Z = accumarray(R,C,[],@(v){v});
>> Z{:}
ans =
1
2
ans =
2
ans =
1
2
ans =
1
2
3

추가 답변 (1개)

Jan
Jan 2018년 4월 26일
편집: Jan 2018년 4월 26일
One loop and one find is enough, easy and very efficient:
A = [60,600,15];
B = [60,512,30,13];
% For each element of B find the indices of elements of A which are
% greater or equal:
D = cell(size(B));
for k = 1:numel(B)
D{k} = find(B(k) <= A);
end
Or with hiding the loop inside cellfun:
D = cellfun(@(b) find(b <= A), num2cell(B), 'UniformOutput', 0)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by