Grouping matrix data into variables when they have the same value in the first column

8 views (last 30 days)
Apologies if this question has been answered somewhere but I have been checking for a while and couldn't find the answer to this specific problem.
I have a matrix of two columns i.e.
{A} {B}
1 22
1 19
1 15
5 12
5 23
5 45
5 1
5 4
6 12
6 12
6 23
6 9
10 2
10 3
10 29
Is there a way I can group the data in column B into variables depending on their value in column A? For example in column B I want 22, 19 and 15 grouped together into a variable, i.e. x, as they all have the same value of 1 in column A. I then want 12, 23, 45, 1 and 4 grouped into a variable, i.e. y, as they all have the same value of 5 in column 1 and so on.
However, the issue I have is that there are around 357 different values of A in Column A and I cannot write them all out manually into the code as it will take forever. Is there a way MATLAB can automatically create the 357 new variables I have shown above automatically by finding all the values in column B which have the same value of A and grouping them? I would then like to obtain the mean and sandard deviation for the data in each of the 357 new data sets.
I hope that is clear enough.
Any help would be greatly appreciated.

Accepted Answer

KSSV
KSSV on 13 May 2020
Let A, B be your first and second column.
[C,ia,ib] = unique(A) ;
N = length(C) ;
iwant = cell(N,1) ;
for i = 1:N
iwant{i} = B(ib==i) ;
end
  4 Comments
KSSV
KSSV on 13 May 2020
You see the dimensions of each cell in iwant will e different. You cannot put them into a matrix. If you want to put them into a matrix, you have to pad NaN or zeros to each cell and make a matrix, Is that okay for you?
sgericeb
sgericeb on 13 May 2020
Yes thanks, I undertand the padding. I'm just not sure how to do it for all 357 new column vectors yet to merge them into a new file

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!