Check if values are sorted without using predifined issorted function
이전 댓글 표시
Hello all, my name is Felipe, and I'm not very experienced in programming, but for a work that I want to apply, I'm being asked for the following tasks, so if anybody could help that would be great!
- Define a vector: [5 4 8 1 5 4 7 4]
- Check if values are sorted (Do not use any predifined sort function)
- In case that the numbers are not sorted, sort them by increasing order.
- After sorting, check if there are any duplicates and remove them, leaving a single value for that number.
- Let the user know the size of the list and if the list has more than 5 items (i.e. “List contains more than 5 items; total items: X”)So I already have made a function but it is not quite polished yet, so I leave it here:
function [sx1] = unt(x)
sx=length(x);
x2=x;
for y = 1:length(x)
[sx(y),ix] = min(x); % crea vector sx de y elementos con el mínimo y su posición ix
x(ix) = []; % borra el mínimo
end
if isequal(sx,x2)
disp('\nIt is sorted')
else
fprintf('\nIt is not sorted - The sorted value is:'); disp(sx);
end
sx1=unique(sx);
fprintf('The value without duplicates is:'); disp(sx1);
i=length(sx1);
if i>5
fprintf('List contains more than 5 items; total items: %d\n',i);
else
fprintf('List contains equal or less than 5 items; total items: %d\n',i);
end
end
First I define the vector x in the command line, then execute the function like this:
x=[5 4 8 1 5 4 7 4];
unt(x)
So I leave this here, in case anyone can help Thanks in advance, Regards
답변 (1개)
Walter Roberson
2017년 2월 22일
0 개 추천
For values sorted in ascending order, and none of the values are inf or nan, then diff() of the vector is never negative.
카테고리
도움말 센터 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!