locate within the first column of a matrix a sequence of numbers and extract those rows

3 views (last 30 days)
hi! I have the matrix 'M'. How can I locate inside the first column of the matrix 'M' the sequence of numbers (1 to #) and extract those rows?
For example, this matrix 'M' breaks down into:
  • rows 1:9
  • rows 10:12
  • rows 13:18

Accepted Answer

Stephen23
Stephen23 on 30 Aug 2024
Edited: Stephen23 on 30 Aug 2024
Use DIFF, which is a key MATLAB function.
M = load('M.mat').M
M = 18x5
1.0000 -0.0394 -0.0204 0.0590 0 2.0000 -0.0429 -0.0225 0.0593 0 3.0000 -0.0398 -0.0201 0.0591 0 4.0000 -0.0431 -0.0224 0.0593 0 5.0000 -0.0400 -0.0200 0.0591 0 6.0000 -0.0431 -0.0223 0.0593 0 7.0000 -0.0399 -0.0202 0.0591 0 8.0000 -0.0398 -0.0203 0.0591 0 9.0000 -0.0401 -0.0200 0.0591 0 1.0000 -0.0376 -0.0140 0.0172 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
X = diff([0;find(diff([M(:,1);0])<0)]);
Y = size(M,2);
C = mat2cell(M,X,Y)
C = 3x1 cell array
{9x5 double} {3x5 double} {6x5 double}
Checking the content:
C{:}
ans = 9x5
1.0000 -0.0394 -0.0204 0.0590 0 2.0000 -0.0429 -0.0225 0.0593 0 3.0000 -0.0398 -0.0201 0.0591 0 4.0000 -0.0431 -0.0224 0.0593 0 5.0000 -0.0400 -0.0200 0.0591 0 6.0000 -0.0431 -0.0223 0.0593 0 7.0000 -0.0399 -0.0202 0.0591 0 8.0000 -0.0398 -0.0203 0.0591 0 9.0000 -0.0401 -0.0200 0.0591 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
ans = 3x5
1.0000 -0.0376 -0.0140 0.0172 0 2.0000 -0.0374 -0.0168 0.0167 0 3.0000 -0.0341 -0.0151 0.0177 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
ans = 6x5
1.0000 -0.0441 -0.0161 0.0761 0 2.0000 -0.0408 -0.0243 0.0753 0 3.0000 -0.0426 -0.0155 0.0761 0 4.0000 -0.0422 -0.0146 0.0761 0 5.0000 -0.0443 -0.0151 0.0762 0 6.0000 -0.0444 -0.0150 0.0762 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!