in a matrix m, how to select the rows after m(m(:,1)==1,2)
조회 수: 7 (최근 30일)
이전 댓글 표시
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!
댓글 수: 0
채택된 답변
추가 답변 (1개)
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
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.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!