2
$\begingroup$

Say I have the following matrix:

$$A = \begin{bmatrix}0.1 & 2 \\ 0.1 & 4 \\ 0.1 & 6 \\ 0.2 & 3 \\ 0.2 & 2 \\ 0.2 & 7 \\ 0.3 & 10 \\ 0.3 & 7 \\ 0.3 & 5 \end{bmatrix}$$

I want this matrix rearranged so that all values in the second column belonging to one specific value in the first column becomes a new row (with the lowest number in the first column becoming the top row). Further, I want the numbers in the left column to become one array containing each number in increasing order. So in this case I want to obtain the following matrix:

$$B = \begin{bmatrix} 2 & 4 & 6 \\ 3 & 2 & 7 \\ 10 & 7 & 5 \end{bmatrix}$$

and the vector:

$$\vec{x} = \begin{bmatrix}0.1 & 0.2 & 0.3 \end{bmatrix}$$

I have written a script in MatLab which works fine to accomplish this, but it requires some for-loops which I would rather avoid as the dataset I will be working on will have more than 100000 rows. My code is as follows:

clear all
A = [.1 2; .1 4; .1 6; .2 3; .2 2; .2 7; .3 10; .3 7; .3 5];
B = size(A);
rown = B(1);
numb = 1;
xs = zeros(1,1);
xs(1)=A(1,1);
for i=1:(rown-1)
    if A(i+1,1) - A(i,1) > 0
        numb = numb + 1;
        xs(numb) = A(i+1,1);
    end
end

col = rown/numb;
B = zeros(numb,col);
m = col;
counter = 1;

for i=1:numb
    B(i,:) = A(counter:m,2)';
    counter = counter + col;
    m = m+col;
end

However, if anyone has some tips as to how I can achieve this without using loops, then I would be very grateful!

(PS: I am unsure as to whether or not this question belongs here or on stackoverflow, bus as Stackoverflow does not accept Latex, I decided to post the question here as I think it is important that I illustrate clearly the problem).

$\endgroup$
  • 1
    $\begingroup$ what if there are, for example, 4 elements for $0.1$, 3 elements for $0.2$ and 3 elements for $0.3$? How large will be $B$? $\endgroup$ – the_candyman Jun 29 '15 at 16:24
  • 1
    $\begingroup$ Hi. With the dataset I will be working on, there will always be the same number of elements for each value in the left column. $\endgroup$ – Kristian Jun 29 '15 at 16:27
5
$\begingroup$

Use reshape:

B=reshape(A(:,2),3,3)

For the second part, it depends on the structure of the first column, but for this specific case you can use the "unique()" function:

x=unique(A(:,1))'
$\endgroup$
  • 1
    $\begingroup$ Wow, thanks a lot! I had no idea it was this easy. I really appreciate it :) $\endgroup$ – Kristian Jun 29 '15 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.