extract a number N of equally spaced rows within a matrix

조회 수: 2 (최근 30일)
Alberto Acri
Alberto Acri 2023년 9월 22일
댓글: Alberto Acri 2023년 9월 24일
HI! I have a number N and a matrix with 100 rows and 2 columns.
How can I recover N rows of the matrix so that they are as equidistant from each other as possible?
For example:
  • with N = 10 I will have 10 rows (row 1, 11, 21, 31,...)
  • with N = 7 I will have 7 rows (row 1, 15, 29,...) In this case the steps are like 100/7 = 14.28 = 14.
a=1:1:100;
a=a';
b=0.1:0.1:10;
b=b';
M=[a,b]; % example matrix
N=10; % number of rows
step = height(M)/N;
step = 14; % round down
v = 1:step:height(M);
M_new = M(v,:);

채택된 답변

Fangjun Jiang
Fangjun Jiang 2023년 9월 22일
편집: Fangjun Jiang 2023년 9월 22일
M=repmat((1:100)',1,2);
N=7;
d=M(round(linspace(1,height(M),N)),:)
d = 7×2
1 1 18 18 34 34 51 51 67 67 84 84 100 100

추가 답변 (1개)

Dyuman Joshi
Dyuman Joshi 2023년 9월 22일
편집: Dyuman Joshi 2023년 9월 22일
You are on the right course -
a=(1:1:100)';
b=(0.1:0.1:10)';
M=[a,b]; % example matrix
N=7; % number of rows
step = height(M)/N
step = 14.2857
%Use floor to round down to nearest integer less than or equal to step
step = floor(step) % round down
step = 14
v = 1:step:height(M)
v = 1×8
1 15 29 43 57 71 85 99
M_new = M(v,:)
M_new = 8×2
1.0000 0.1000 15.0000 1.5000 29.0000 2.9000 43.0000 4.3000 57.0000 5.7000 71.0000 7.1000 85.0000 8.5000 99.0000 9.9000
  댓글 수: 8
Dyuman Joshi
Dyuman Joshi 2023년 9월 24일
편집: Dyuman Joshi 2023년 9월 24일
"when height(M) is 100 and N is 10, it is hard to say which one is the right answer."
OP has specified what the expected outcome is and the logic behind it -
HI! I have a number N and a matrix with 100 rows and 2 columns.
How can I recover N rows of the matrix so that they are as equidistant from each other as possible?
For example:
  • with N = 10 I will have 10 rows (row 1, 11, 21, 31,...)
  • with N = 7 I will have 7 rows (row 1, 15, 29,...) In this case the steps are like 100/7 = 14.28 = 14.
Alberto Acri
Alberto Acri 2023년 9월 24일
Thanks for the replies!
@Fangjun Jiang Yes, it is actually impossible to make an "equally spaced" distribution for any value of N but your case is more useful for my purpose.
@Dyuman Joshi Your solution is certainly fine too. I gave an example to make it clear what I wanted to achieve as a final result. The distribution as you wrote it follows exactly what I wanted to obtain as a result in the question. But it was an example. You'll accept both as an answer but that's not possible.

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

카테고리

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

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by