How to select specific elements in a matrix?

43 ビュー (過去 30 日間)
Tin Nguyen
Tin Nguyen 2015 年 10 月 10 日
コメント済み: the cyclist 2015 年 10 月 11 日
Say I have a 10x10 matrix
x =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
And I want to select a certain element from each row in the matrix for example: I want elements from row 1 column 3, row 2 column 4, row 4 column 3, row 5 column 3 and turn those element into 0. I know I can do something like:
x(1,3)=0;
x(2,4)=0;
etc. But that is time-consuming. Is there a code that I can just write all that in one line? I thought it would be something like:
x=([1 2 3 4], [3 4 3 3])=0;

回答 (1 件)

the cyclist
the cyclist 2015 年 10 月 10 日
Yes, but you have to use "linear indices":
x = [
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9]
linearIndices = sub2ind(size(x),[1 2 3 4], [3 4 3 3])
x(linearIndices) = 0
  3 件のコメント
Tin Nguyen
Tin Nguyen 2015 年 10 月 10 日
Thank you so much! That worked perfectly :) !
the cyclist
the cyclist 2015 年 10 月 11 日
The best form of thanks is accepting a solution that worked for you. (This rewards the person who helped you, and also may help future people with a similar question.)

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by