grouping array based on similar row element

Hello,
I have a matrix A:
123 1970 1 1 12
123 1971 1 1 120
123 1972 1 12 300
240 1970 1 10 40
240 1971 2 1 45
240 1972 3 34 56
230 1970 1 2 120
230 1971 2 3 320
230 1972 1 14 360
I wish to export 3 different matrices in a folder based on the common column element. This might be easy without a loop using an index operation. The resulting matrices
A =
123 1970 1 1 12
123 1971 1 1 120
123 1972 1 12 300
B =
240 1970 1 10 40
240 1971 2 1 45
240 1972 3 34 56
C =
230 1970 1 2 120
230 1971 2 3 320
230 1972 1 14 360

3 commentaires

Guillaume
Guillaume le 8 Jan 2020
Is the last row of C correct, shouldn't that be in B?
Poulomi Ganguli
Poulomi Ganguli le 8 Jan 2020
Modifié(e) : Poulomi Ganguli le 8 Jan 2020
yes, the last row of C should be in B. sorry. Corrected now.
It's pretty universal among experienced MATLAB users that that would be a bad idea.
Now, if you want ot do it in a loop
uniqueValues = unique(A(:, 1));
for k = 1 : length(uniqueValues)
thisValue = uniqueValues(k);
rowsWithThisValue = A(:, 1) == thisValue;
subArray = A(rowsWithThisValue, :)
% Now do something with the subArray
end
then that would be okay.

Connectez-vous pour commenter.

 Réponse acceptée

Guillaume
Guillaume le 8 Jan 2020
The easiest:
savelocation = 'C:\somewhere\somefolder';
fileformat = 'submatrices_%02d.txt';
group = findgroups(A(:, 1));
splitapply(@(subA, index) writematrix(subA, fullfile(savelocation, sprintf(fileformat, index(1)))), A, group, group); %passing group twice so we get it in the anonymous function to use as file number

3 commentaires

Poulomi Ganguli
Poulomi Ganguli le 9 Jan 2020
Modifié(e) : Poulomi Ganguli le 9 Jan 2020
I wanted to specify 123.txt, 240.txt and 230.txt as file names, so I revised the last line a little:
splitapply(@(subA, index) writematrix(subA, fullfile(Save_Location, sprintf(fileformat, subA(index(1)))),'Delimiter',' '),A,group,group);
Or simpler:
splitapply(@(subA) writematrix(subA, fullfile(Save_Location, sprintf('%d.txt', subA(1))), 'Delimiter', ' '), A, group);
lim xiang
lim xiang le 16 Juil 2020
Hi, I am new to Matlab. May you help to explain the code ? Thank you

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by