How do I create this sorting function?

Hi all. I am still a bit new to Matlab and I was asked to create a function with one input (X) and one output (Y) which ranks any set of numbers in such a way that for instance if X=[5 2 9 7], Y=[2 1 4 3]. This is to be done through the use of loops and logical operators. How would I go about doing this please? Thanks in advance.

답변 (1개)

Dyuman Joshi
Dyuman Joshi 2022년 5월 3일
편집: Dyuman Joshi 2022년 5월 4일

0 개 추천

For all unique values
input = [5 2 9 7];
output = sorting(input)
output = 1×4
2 1 4 3
function y = sorting(x)
for i=1:numel(x)
y(i)=nnz(x(i)>=x); %you can use sum as well
end
end

댓글 수: 3

Nico Degabriele
Nico Degabriele 2022년 5월 4일
Thanks so much! However, is there a way to go around using numel and nnz please?
Walter Roberson
Walter Roberson 2022년 5월 4일
numel(x) is defined as the prod(size(x))
As @Dyuman Joshi indicates, you can use sum() instead of nnz()
Walter Roberson
Walter Roberson 2022년 5월 4일
편집: Walter Roberson 2022년 5월 4일
Note: that sorting() function does not work if there are duplicate entries, and will return 0 for any entry that is NaN.

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2022년 5월 3일

편집:

2022년 5월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by