user3161344
user3161344

Reputation: 83

Store values from exisiting matrix into new matrix

I have a matrix containing 8 cols and 80k rows. (From an excel file)

Each row has an ID.

I want to store all data with ID no. 1 in a new matrix. And all data with ID no. 2 in a second matrix etc. So each time an ID changes I want to save all the data of a new ID in a new matrix.

There are above 800 ID's.

Ive tried several things w/o luck. Among others:

    k = zeros(117,8)
for i =1:80000
    k(i) = i + Dataset(1:i,:)
end

The above was only to see if I actually could get the first 117 rows saved in another matrix which didnt succeed.

Upvotes: 0

Views: 42

Answers (1)

kabdulla
kabdulla

Reputation: 5429

If one of the 8 columns contains the ID then you can use logical indexing. For example if column 1 contains the ID, we can first find a list of all different ID values:

uniqueIDs = unique(Dataset(:, 1));

Then we can create cell array, with the lists of items of a given ID:

listsByID = cell(length(uniqueIDs), 1);
for idx = 1:length(uniqueIDs)
    listsByID{idx} = Dataset(Dataset(:, 1) == uniqueIDs(idx), :);
end

Running the above on an example dataset:

Dataset = [1 0.1 10
           1 0.2 20
           2 0.3 30
           3 0.4 40
           2 0.5 50
           2 0.6 60];

Results in:

1.0000 0.1000 10.0000
1.0000 0.2000 20.0000

2.0000 0.3000 30.0000
2.0000 0.5000 50.0000
2.0000 0.6000 60.0000

3.0000 0.4000 40.0000

Upvotes: 3

Related Questions