How to replace values of certain rows in a matrix?

34 ビュー (過去 30 日間)
Salad Box
Salad Box 2019 年 10 月 18 日
編集済み: dpb 2019 年 10 月 18 日
Hi,
I have a matrix "a"
a =
1 1
2 2
3 3
4 4
I would like to replace the 2nd and 3rd row in "a" with "b" = [0 0]. So I want to change "a" to
a =
1 1
0 0
0 0
4 4
Do I have to do it in a loop? Can I avoid the loop?

回答 (1 件)

Adam
Adam 2019 年 10 月 18 日
編集済み: Adam 2019 年 10 月 18 日
a( [2 3], : ) = repmat( b, 2, 1 )
A bit more generally:
indicesToReplace = [2 3];
a( [2 3], : ) = repmat( b, indicesToReplace, 1 );
  1 件のコメント
dpb
dpb 2019 年 10 月 18 日
編集済み: dpb 2019 年 10 月 18 日
For the OP's specific case of replacing with a constant, automagic expansion negates need for repmat.
a(indicesToReplace,:)=0;
Side note to OP--work through the example tutorials in the "Getting Started" documentation link to get a feel for basic MATLAB syntax and addressing modes including colon and friends...will be an investment in time paid back many times over.

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by