Extract rows from a matrix considering continuous numbers in the first column
1 view (last 30 days)
Show older comments
Alberto Acri
on 23 Aug 2023
Commented: Alberto Acri
on 23 Aug 2023
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];
1 Comment
Accepted Answer
Bruno Luong
on 23 Aug 2023
Edited: Bruno Luong
on 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))
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{:}
2 Comments
Bruno Luong
on 23 Aug 2023
Edited: Bruno Luong
on 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}
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays 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!