find the three smallest values in a vector in matlab

You can use the sort function to sort the elements of the vector in ascending order and then select the first three elements using indexing. Another option is to use the min function three times, each time excluding the minimum value found in the previous iteration. Here's an example of both methods:

main.m
% Example vector
v = [6, 3, 8, 2, 5, 1, 9, 4, 7];

% Method 1: sort and index
sorted_v = sort(v);
smallest_three = sorted_v(1:3);

% Method 2: use min function
min1 = min(v);
v2 = v(v~=min1);
min2 = min(v2);
v3 = v2(v2~=min2);
min3 = min(v3);
smallest_three = [min1, min2, min3];
280 chars
15 lines

Both methods will give you the same result in the variable smallest_three, which will be a vector with the three smallest values in v.

related categories

gistlibby LogSnag