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

3 ビュー (過去 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 件のコメント
Loriann Chevalier
Loriann Chevalier 2022 年 7 月 12 日
That's great. Thank you very much

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by