Filter löschen
Filter löschen

Extract rows from a matrix considering continuous numbers in the first column

1 Ansicht (letzte 30 Tage)
Hi! I would need to extract from the matrix 'matrix' the rows that start at 'r_max_total' and extend to the top and bottom rows of 'matrix' until the values in the first column of 'matrix' stop.
Basically, I have this matrix and the starting row ('r_max_total'):
matrix = ...
[60 210 96 92 398
62 336 196 212 744
63 472 285 307 1064
64 603 426 440 1469
65 611 472 489 1572
66 691 627 581 1899
67 629 611 563 1803
68 560 617 596 1773
69 492 561 532 1585
72 284 451 450 1185];
max_total = max(matrix(:,5));
[r_max_total,c_max_total] = find(matrix(:,5) == max_total);
and the matrix I need to get must be this:
matrix_out = ...
[62 336 196 212 744
63 472 285 307 1064
64 603 426 440 1469
65 611 472 489 1572
66 691 627 581 1899
67 629 611 563 1803
68 560 617 596 1773
69 492 561 532 1585];

Akzeptierte Antwort

Bruno Luong
Bruno Luong am 23 Aug. 2023
Bearbeitet: Bruno Luong am 23 Aug. 2023
For multiple values of rmax (in a vector)
matrix = ...
[59 1 2 3 1899 % I invent it
60 210 96 92 398
62 336 196 212 744
63 472 285 307 1064
64 603 426 440 1469
65 611 472 489 1572
66 691 627 581 1899
67 629 611 563 1803
68 560 617 596 1773
69 492 561 532 1585
72 284 451 450 1185
73 1 2 3 1899 % I invent it
];
A5 = matrix(:,5);
rmax = find(A5 == max(A5))
rmax = 3×1
1 7 12
A1 = matrix(:,1);
idx = find([true; diff(A1)~=1; true]);
loc = discretize(rmax, idx);
if any(isnan(loc) | loc==length(idx))
error('incorrect rmax');
end
Ac = arrayfun(@(loc) matrix(idx(loc):idx(loc+1)-1,:), loc, 'unif', 0);
Ac{:}
ans = 2×5
59 1 2 3 1899 60 210 96 92 398
ans = 8×5
62 336 196 212 744 63 472 285 307 1064 64 603 426 440 1469 65 611 472 489 1572 66 691 627 581 1899 67 629 611 563 1803 68 560 617 596 1773 69 492 561 532 1585
ans = 2×5
72 284 451 450 1185 73 1 2 3 1899
  2 Kommentare
Bruno Luong
Bruno Luong am 23 Aug. 2023
Bearbeitet: Bruno Luong am 23 Aug. 2023
% ... as previously then
nrows = cellfun('size', Ac, 1); % this is the same as nrows = idx(loc+1)-idx(loc)
[~,imax] = max(nrows)
Aselected = Ac{imax}

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by