I'm using MATLAB R2017a. While trying to use "mink" and "maxk" functions, the MATLAB responds "Undefined function or variable 'maxk'." These two functions were introduced in R2017b. Is it possible to use these functions with R2017a? if yes, then how?

1 件のコメント

Stephen23
Stephen23 2018 年 2 月 5 日
"These two functions were introduced in R2017b. Is it possible to use these functions with R2017a?"
No.

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

 採用された回答

Birdman
Birdman 2018 年 2 月 5 日

0 投票

One approach would be writing your own function:
function y=mink(A,k)
A=sort(unique(A));
y=A(1:k);
end
Call this function from command line as follows
A=1:10;
mink(A,3)
and the first three smallest elements will be displayed.

7 件のコメント

UET Hussain
UET Hussain 2018 年 2 月 5 日
Its good. Thank you for response. What about maximum values? mink(A,3) will simply give me the first three values of my array. how to get the last 3?
Stephen23
Stephen23 2018 年 2 月 5 日
The output of unique is already sorted, so sort is unnecessary.
Birdman
Birdman 2018 年 2 月 5 日
function y=maxk(A,k)
A=sort(unique(A),'descend');
y=A(1:k);
end
and then from command line:
A=1:10;
maxk(A,3)
UET Hussain
UET Hussain 2018 年 2 月 5 日
Got it...... @Birdman Thank you Sir.
Birdman
Birdman 2018 年 2 月 5 日
編集済み: Birdman 2018 年 2 月 5 日
You are welcome. You can officially thank me by accepting my answer.
Jan
Jan 2018 年 2 月 5 日
mink does not reply unique elements. Therefore the correct replacement is:
function y = mink(A, k)
A = sort(A); % No UNIQUE here
y = A(1:k);
end
See: mink([1,1,2,3], 2) replies [1,1,2] .
Birdman
Birdman 2018 年 2 月 5 日
Mine approach was different, but anyway thanks Jan :)

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

その他の回答 (1 件)

Salam Ismaeel
Salam Ismaeel 2018 年 9 月 4 日
編集済み: Salam Ismaeel 2018 年 9 月 4 日

0 投票

% function [B BIndex RestVector]= maxk2(A, k)
% Find k largest elements in a Vector A
% B : Vector with all max elements (included repeated)
% BIndex : idx of max k element
% RestVector : rest of the elements without max k elements
function [B BIndex RestVector]= maxk2(A, k)
B = 0;
RestVector = A;
sumIndex = 1;
for i=1:k
MaxA = max(A);
I = A == MaxA;
sumI = sum(I); %To find number of Max elements (repeated)
B(sumIndex: sumIndex+sumI-1) = MaxA; % to same max elements in B
BIndex(sumIndex: sumIndex+sumI-1) = find(A == MaxA);
sumIndex = sumIndex + sumI;
A(I) = min(A); % exchange the max elements by a smallest value
end
RestVector(BIndex) = []; % remove largest values
------------------------------ Example ------------------
>> x
x =
4 17 65 73 65 45 55 30 74 19
>> [x1 x1idx x1new ] = maxk2(x,4)
x1 =
74 73 65 65 55
x1idx =
9 4 3 5 7
x1new =
4 17

1 件のコメント

UET Hussain
UET Hussain 2018 年 9 月 5 日
Sir Sir Sir, slightly difficult approach. but its giving all required things. thanks for response.

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by