필터 지우기
필터 지우기

find minumum indices of one array in another array

조회 수: 1 (최근 30일)
Limei Cheng
Limei Cheng 2020년 8월 11일
댓글: Limei Cheng 2020년 8월 11일
I have two arrays as below:
A= [ 47 100 153 207 261 314 368 422 474 527 581 635 687 741 794 847 900 954 1007 1060];
B=[301 602 903];
I'm trying find the indexA = [5 11 17] such that the corresponding elements in A(indexA)=[261 581 900] is the largest element that smaller than B. i.e.
A(indexA(i)) <=B(i) and is the largest element in A that smaller than B(i).
Here is my code using for loop:
for i=1:length(B)
indexA=length(find(A<=B(i));
end
Is there more simple way without using for loop?

채택된 답변

Fangjun Jiang
Fangjun Jiang 2020년 8월 11일
편집: Fangjun Jiang 2020년 8월 11일
You have the assumption that A is incremental. If it is always true, it can be done like this.
%%
A= [ 47 100 153 207 261 314 368 422 474 527 581 635 687 741 794 847 900 954 1007 1060];
B=[301 602 903];
indexA=sum(A'<=B)
indexA =
5 11 17
If A is not always incremental, you could do this. The one thing that you might not have been aware of is called "implict expansion", like C=A'-B in this case. In MATLAB® R2016b and later, you can directly use operators instead of bsxfun(), since the operators independently support implicit expansion of arrays with compatible sizes.
%%
A= [ 47 100 153 207 261 314 368 422 474 527 581 635 687 741 794 847 900 954 1007 1060];
B=[301 602 903];
C=A'-B;
C(C>=0)=nan;
[~,indexA]=max(C)
indexA =
5 11 17
  댓글 수: 1
Limei Cheng
Limei Cheng 2020년 8월 11일
Thx a lot. This one is about 4 times faster than my for loop solution
.

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

추가 답변 (1개)

Bruno Luong
Bruno Luong 2020년 8월 11일
A= [ 47 100 153 207 261 314 368 422 474 527 581 635 687 741 794 847 900 954 1007 1060];
B=[301 602 903];
[~,idxA]=histc(B,A)
Result
idxA =
5 11 17
  댓글 수: 4
Limei Cheng
Limei Cheng 2020년 8월 11일
good job. Thx a lot. It's really fast.
Limei Cheng
Limei Cheng 2020년 8월 11일
Can I use the histc function inside a parfor loop?

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by