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!

采纳的回答

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 个评论
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