# I am triying to rearranging the matrix and form one as explained below

1 Ansicht (letzte 30 Tage)
Hems am 13 Okt. 2016
Bearbeitet: James Tursa am 13 Okt. 2016
I would like to rearrange and form a new matrix, I have a matrix for example A=[1 2;2 16;3 5;1 12;2 6;3 7;1 5;2 7;3 6;1 7;2 10;3 18] this has repetitive 1st column "1 2 3 " I need to form a new martix with values in the 2nd row arranged corrosponding values resulting B=[1 2 12 5 7;2 16 6 7 10;3 5 7 6 18] Please help ,how this can be done? TIA!
##### 1 KommentarKeine anzeigenKeine ausblenden
Alexandra Harkai am 13 Okt. 2016
Bearbeitet: Alexandra Harkai am 13 Okt. 2016
Using splitapply could be a good option, since your matrix seems to be defining the group indices (1,2,3) and the corresponding values:
splitapply(@(x) {x'}, A(:,2), A(:,1))
This does not give you a matrix yet, but is able to deal with the situation even when not all groups have the same number of elements. Plus you can then append the group indices in front of the result matrix, but this is a good direction to start in. Explanation: @(x) {x'} is basically an identity function, but transposing the result. You just want to apply the identity function to each group of elements, which is what splitapply does.

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Ganesh Hegade am 13 Okt. 2016
Bearbeitet: James Tursa am 13 Okt. 2016
aSize = size(A);
initialValue = A(1);
count = 1;
temp=[];
for i = 1: aSize(1)
if i >1 && A(i) == initialValue
[B] = A(count:i -1, :) ;
count = i;
temp = [temp B];
end;
end;
bSize = size(temp);
temp = [temp A(i- bSize(1) + 1:i, :)];
B = unique(temp.','rows', 'stable').';
Thanks.
##### 1 KommentarKeine anzeigenKeine ausblenden
Guillaume am 13 Okt. 2016
Please, use the {} Code button (or put two spaces in front of each line of code) to format code as code

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

Guillaume am 13 Okt. 2016
Following on from Alexandra Harkai's comment to your question:
A = [1 2;2 16;3 5;1 12;2 6;3 7;1 5;2 7;3 6;1 7;2 10;3 18]
rows = splitapply(@(x) {x'}, A(:,2), A(:,1))
assert(all(diff(cellfun(@numel, rows)) == 0), 'Cannot make a matrix since each unique index does not have the same number of elements');
B = [unique(A(:, 1)), vertcat(rows{:})]
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Find more on Operators and Elementary Operations in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by