in a matrix m, how to select the rows after m(m(:,1)==1,2)

조회 수: 7 (최근 30일)
Loriann Chevalier
Loriann Chevalier 2022년 7월 12일
댓글: dpb 2022년 7월 12일
Hi everyone,
I have a matrix, say 13x2 like this :
m = [0 0;
0 0;
0 0;
0 0;
0 0;
1 0;
0 0;
0 0;
0 0;
0 0;
0 0;
0 0;
0 0]
Now I want to set that at the row where column 1 has a value of 1, the value of the same row in column 2 is 0.25, and also the 3 next rows (still column 2), i.e., I ultimately want this :
m = [0 0;
0 0;
0 0;
0 0;
0 0;
1 0.25;
0 0.25;
0 0.25;
0 0.25;
0 0;
0 0;
0 0;
0 0]
For the row with m(row,1) = 1, I use this :
m(m(:,1)==1,2) = 0.25;
but then I cannot find the right notation for the 3 next rows. E.g. I would imagine this below, but it doesn't work :
m((m(:,1)==1):(m(:,1)==1)+3,2) = 0.25;
Thanks!

채택된 답변

dpb
dpb 2022년 7월 12일
편집: dpb 2022년 7월 12일
Don't try to play MATLAB golf; use a temporary variable to help...
ix=find(m); % ~=0 is implied; only the one element is nonzero
m(ix:ix+3,2)=0.25; % set the desired column 2 values

추가 답변 (1개)

Sanyam
Sanyam 2022년 7월 12일
Answer of @dpb is cool, but if you don't remember the syntax to perform vectorized operations in MATLAB, then writing the code from basics help a lot. Below is the snippet of code attached, accomplishing your task with just if-else and for-loop
Explanation:
  • iterate over all the rows
  • check if the value in first column is 1
  • if not then do nothing
  • if one then change the value of 2nd column to 0.25 -> change the value of 2nd column of next 2 rows, given the rows lie inside your matrix
Hope it's useful. Thanks!!
for i = 1:size(m, 1)
if m(i, 1) == 1
m(i, 2) = 0.25;
if i+1 <= size(m, 1)
m(i+1, 2) = 0.25;
end
if i+2 <= size(m, 1)
m(i+2, 2) = 0.25;
end
end
end
  댓글 수: 2
Loriann Chevalier
Loriann Chevalier 2022년 7월 12일
thank you for the additional insight :)
dpb
dpb 2022년 7월 12일
" if you don't remember the syntax to perform vectorized operations in MATLAB, ..."
In that case, there's almost no point in using MATLAB...if one isn't going to take advantage of its power.

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

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by