フィルターのクリア

find two minimum values not followed by each other.

1 回表示 (過去 30 日間)
FV
FV 2020 年 4 月 19 日
コメント済み: Ameer Hamza 2020 年 4 月 20 日
I am using mink(A,2) to find the two smallest values, but I need to find the two smallest values not followed by each other. How can this be done?
To illustrate: A(1; 1.2; 1.2; 0.7; 0.6; 0.61; 1; 1; 1.2;0.65) I want to find 0.6 and 0.65 and not 0.6 and 0.61.
  1 件のコメント
FV
FV 2020 年 4 月 19 日
I also need to find the index of the values.

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

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 4 月 19 日
編集済み: Ameer Hamza 2020 年 4 月 20 日
Try this. It also preserve the order of minumum values
A = [0.65;1.2;1.2;0.7;0.6;0.61;1;1;1.2;1];
[vals,idx] = mink(A,3);
if diff(idx(1:2))==1
I = sort(idx([1 3]));
min_vals = A(I);
else
I = sort(idx([1 3]));
min_vals = A(I);
end
Result:
I =
1
5
min_vals =
0.6500
0.6000
  2 件のコメント
FV
FV 2020 年 4 月 20 日
Looks good, How can I get the index of the result?
Ameer Hamza
Ameer Hamza 2020 年 4 月 20 日
See the updated code.

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

その他の回答 (2 件)

Mehmed Saad
Mehmed Saad 2020 年 4 月 19 日
編集済み: Mehmed Saad 2020 年 4 月 19 日
The long Method
A=[1;1.2;1.2;0.7;0.6;0.61;1;1;1.2;0.65];
miny = [];
for i =1:3
x = min(A);
A(A==x) = [];
if(i~=2)
miny = [miny x];
end
end
miny
The short one
A=[1;1.2;1.2;0.7;0.6;0.61;1;1;1.2;0.65];
B = sort(A);
miny = [B(1) B(3)]
  3 件のコメント
Image Analyst
Image Analyst 2020 年 4 月 19 日
So the long method is too long, but the short method is too short. Exactly how many lines of code do you want?
FV
FV 2020 年 4 月 19 日
I don't want to sort it and therefore the short one doesn't work. I also need it to work for other A's.

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


Image Analyst
Image Analyst 2020 年 4 月 19 日
Try this:
A=[1;1.2;1.2;0.7;0.6;0.61;1;1;1.2;0.65];
% Plot, just for fun.
plot(A, 'r.-', 'MarkerSize', 30);
grid on;
% Find the values in ascending order, so the min value will be at location/index = 1.
[sortedA, sortOrder] = sort(A, 'Ascend')
% Now find the second lowest value but it can't be in the location next to the lowest value.
% Use diff() to see how many indexes the values are separated by each other by.
d = diff(sortOrder) % Don't want 1's
% Get min1 and min2 according to the non-consecutive criteria.
min1 = sortedA(1)
if d(1) ~= 1
% Not consecutive so we're OK.
min2 = sortedA(2) % Get the next one
else
% Consecutive so pick the next location with the next lowest value.
min2 = sortedA(3)
end
If it's homework, don't turn in my work as your own or you could get into trouble with your instructor.
  1 件のコメント
FV
FV 2020 年 4 月 19 日
This code also just work for this problem. Sometimes it's no smaller values beside the smallest one.
This is not a homework.

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by