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

조회 수: 1 (최근 30일)
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];

채택된 답변

Bruno Luong
Bruno Luong 2023년 8월 23일
편집: Bruno Luong 2023년 8월 23일
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
Bruno Luong
Bruno Luong 2023년 8월 23일
편집: Bruno Luong 2023년 8월 23일
% ... 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}

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by