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

Thread Subject:
Insertionsort 2 vectors

Subject: Insertionsort 2 vectors

From: Christian

Date: 11 May, 2014 20:32:09

Message: 1 of 2

Hi

I got 2 vectors. A is generated by randperm. B is a userinput to the number in A.

A = [5 3 4 1 2]

B = [0 -1 1 0 0]

I want to sort A from 1-5 but B has to be in the same order, like this (A = [1 2 3 4 5] and B = [0 0 -1 1 0]. I thought this would work, but only A is being shown in the right order, and B is just not right. What can I do?

for j = 1:length(A)
    pivot = A(j);
    while ((j > 1) && (A(j - 1) > pivot))
        A(j) = A(j - 1);
        B(j) = B(j - 1);
        j = j - 1;
    end
    A(j) = pivot;
end

end

Subject: Insertionsort 2 vectors

From: dpb

Date: 11 May, 2014 20:41:28

Message: 2 of 2

On 5/11/2014 3:32 PM, Christian wrote:
> I [have] 2 vectors. A is generated by randperm. B is a userinput to the
> number in A.
> A = [5 3 4 1 2]
>
> B = [0 -1 1 0 0]
>
> I want to sort A from 1-5 but B has to be in the same order, ...

Several choices (as almost always :) )...

C=sortrows([A.' B.']);

or

[A,ia]=sort(A);
B=B(ia);

Takes your pick or salt to suit the end objective...

--

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us