# Math Help - MATLAB Help-Sort with Carry

1. ## MATLAB Help-Sort with Carry

Problem: Write a function to sort one real array into ascending order while carrying along a second one. Test the function with the following two 9-element arrays:
a=[1,11,-6,17,-23,0,5,1,-1]
b=[31,101,36,-17,0,10,-8,-1,-1]

This problem is asking that you sort array a into ascending order, while simultaneously carrying a along a second array b. In such a sort, each time an element of array a is exchanged with another element of array a, the corresponding elements of array b are also swapped. When the sort is over, the elements of array a are in ascending order, while the elements of array b that were associated with particular elements of array a are still associated with them.

This is what I have so far:
clc
nvals=input('Enter numbers of values to sort for array1: ')
array1=zeros(1,nvals);
for ii=1:nvals;
string=['Enter value ' int2str(ii) ': '];
array1(ii)=input(string);
end
sorted = sort(array1);
fprintf('\nSorted data for array1:\n');
for ii=1:nvals
fprintf(' %8.4f\n',sorted(ii));
end

This asks the user to input an amount of number values and from those values it sorts the array into ascending order. I don't know any command that can bind the elements in each of these two arrays and rearrange array b according to the rearranged array a.

2. Originally Posted by Battousia
Problem: Write a function to sort one real array into ascending order while carrying along a second one. Test the function with the following two 9-element arrays:
a=[1,11,-6,17,-23,0,5,1,-1]
b=[31,101,36,-17,0,10,-8,-1,-1]

This problem is asking that you sort array a into ascending order, while simultaneously carrying a along a second array b. In such a sort, each time an element of array a is exchanged with another element of array a, the corresponding elements of array b are also swapped. When the sort is over, the elements of array a are in ascending order, while the elements of array b that were associated with particular elements of array a are still associated with them.

This is what I have so far:
clc
nvals=input('Enter numbers of values to sort for array1: ')
array1=zeros(1,nvals);
for ii=1:nvals;
string=['Enter value ' int2str(ii) ': '];
array1(ii)=input(string);
end
sorted = sort(array1);
fprintf('\nSorted data for array1:\n');
for ii=1:nvals
fprintf(' %8.4f\n',sorted(ii));
end

This asks the user to input an amount of number values and from those values it sorts the array into ascending order. I don't know any command that can bind the elements in each of these two arrays and rearrange array b according to the rearranged array a.
Code:
[AA, Idx]=sort(a);
BB=b(Idx);
Code:
>> a=[1,11,-6,17,-23,0,5,1,-1]
a =
1  11  -6  17 -23   0   5   1  -1

>> b=[31,101,36,-17,0,10,-8,-1,-1]
b =
31 101  36 -17   0  10  -8  -1  -1

>> [AA,Idx]=sort(a)
AA =
-23  -6  -1   0   1   1   5  11  17

Idx =
5 3 9 6 1 8 7 2 4

>> BB=b(Idx)
BB =
0  36  -1  10  31  -1  -8 101 -17
CB