user1849133
user1849133

Reputation: 527

MatLab to convert a matrix with respect to 1st col

This question is an outgrowth of MatLab (or any other language) to convert a matrix or a csv to put 2nd column values to the same row if 1st column value is the same? and Group values in different rows by their first-column index

If

      A = [2 3 234 ; 2 44 99999; 2 99999 99999; 3 123 99; 3 1232 45; 5 99999 57]

1st column |  2nd column | 3rd column
--------------------------------------
2             3          234
2             44         99999
2             99999      99999
3             123        99
3             1232       45
5             99999        57

I want to make

1st col |  2nd col | 3rd col | 4th col | 5th col | 6th col| 7th col
--------------------------------------------------------------------
2         3        234       44       
3         123      99        1232      45
5         57

That is, for each numbers in the 1st col of A, I want to put numbers EXCEPT "99999"

If we disregard the "except 99999" part, we can code as Group values in different rows by their first-column index

[U, ix, iu] = unique(A(:,1));
vals = reshape(A(:, 2:end).', [], 1);                    %'// Columnize values
subs = reshape(iu(:, ones(size(A, 2) - 1, 1)).', [], 1); %'// Replicate indices
r = accumarray(subs, vals, [], @(x){x'});

But obviously this code won't ignore 99999.

I guess there are two ways

1. first make r, and then remove 99999
2. remove 99999 first, and then make r

Whichever, I just want faster one.

Thank you in advance!

Upvotes: 1

Views: 143

Answers (1)

Marcin
Marcin

Reputation: 238229

I think options 1 is better, i.e. first make r, and then remove 99999. Having r, u can remove 99999 as follows:

r2 = {}; % new cell array without 99999

for i = 1:numel(r)    
    rCell = r{i};
    whereIs9999 = rCell == 99999; 
    rCell(whereIs9999) = []; % remove 99999
    r2{i} = rCell;
end

Or more fancy way:

r2= cellfun(@(c) {c(c~=99999)}, r);

Upvotes: 1

Related Questions