Alternative to 'find' which won't return multiple values?

조회 수: 3 (최근 30일)
Stephen
Stephen 2019년 3월 23일
댓글: Stephen 2019년 3월 25일
Hello,
I am running the following code, which works most of the time but occasionally causes issues. The problem is that ocassionally the values in 'topfit' will have more than 1 match in the matrix 'totalsale', so the 'position' variable is not a constant size. Due to the nature of the rest of the code it is imperative position be just 10 figures.
I have tried just limiting position to 10 figures manually by setting position = position(1:10,:) but that has it's own problems.
position = find(ismember(totalsale,topfit)); %check the numbers in topfit that match totalsale
topstack = finalpop(position,:);
finalpop is a 100x16 matrix.
Totalsale is a 100x1 matrix of the fitness values of the rows in finalpop.
Topfit is a 10x1 matrix, the top 10 totalsale fitness values, in descending order.
Can anyone recommend a way to return only the 10 rows in finalpop which produced the top 10 fitness values? Could I assign each a number 1-10 and somehow assign that to finalpop to find them? Stuck for ideas. Thanks!
For reference:
If the fitness values produced were : 100,99,98,97,96,95,94,93,92,91,91,91,91
I would like to return the finalpop values that produced the first 10 and ignore the other three 91 values, even though they are just as fit.

채택된 답변

dpb
dpb 2019년 3월 23일
편집: dpb 2019년 3월 23일
If you're using R2017b or later...
[~,i10mx]=maxk(topfit,10); % return 10 largest positions in topfit vector
topstack = finalpop(i10mx,:); % look up those in the array
NB: Unless there's other need for it, there's no reason to make a separate variable topfit just for the winners--just refernce the proper column index of the overall array.
  댓글 수: 2
dpb
dpb 2019년 3월 23일
Oh, now I see Steven beat me to it... :)
Stephen
Stephen 2019년 3월 25일
This did the trick! Thank you!

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

추가 답변 (1개)

Steven Lord
Steven Lord 2019년 3월 23일
The find function allows you to request the first N or the last N non-zero elements of the input array. Those are maximum limits; if you ask it to return the first 5 non-zero elements of an array that only has 3 non-zero elements, you're only going to get those three.
But since you mentioned looking for some maximum values, the maxk function may also be of interest to you.

카테고리

Help CenterFile Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by