MATLAB Answers


how can I create a vector with unknown length?

Asked by sapir
on 9 May 2013

I need to create a user defined function that recieves a vector x of any length and than sorts the vector from the largest to the smallest into a new vector y. I'm not allowed to use the function sort. I have no idea how to begin! please help me!! thank u!!!


Log in to comment.


No products are associated with this question.

3 Answers

Answer by Roger Stafford on 9 May 2013

This article should be of help to you.

I tend to prefer the merge sort algorithm.


Log in to comment.

Answer by John Doe
on 9 May 2013
Edited by John Doe
on 9 May 2013

The most intuitive (and simple to implement) is probably bubble sort:

Since this is an assignment, I'll leave some of it open, so fill in the blanks =)

for j=1:1:n-1
    % comparing each number with the next and swapping
    for i=1:1:n-1
       if ...
      % In here you should check if A(i) > A(i+1)
      % If so, switch places. You need a temporary
      % variable, in order to not overwrite something.

Good luck =)


Log in to comment.

Answer by Sean de Wolski
on 9 May 2013

xsorted = sortrows(x(:),-1)


Log in to comment.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!