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

7 views (last 30 days)
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!

Accepted Answer

dpb
dpb on 12 Jul 2022
Edited: dpb on 12 Jul 2022
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

More Answers (1)

Sanyam
Sanyam on 12 Jul 2022
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 Comments
dpb
dpb on 12 Jul 2022
" 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.

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!