Change the value of a matrix according to the indexes stored in another one.

2 ビュー (過去 30 日間)
Hey, goodies, let's pretend I have the next matrix.
Z = zeros(5,6);
And in another matrix called idx I have the information of which rows and columns of Z I want to change the value, for example:
idx = [1 1; 2 5; 4 6]
Being the first column the position of the columns I want to change and the value of the second idx column the position of the rows I want to change, and if the value i want to obtein in Z in idx position is 5, what i expect to have is:
This is just an example, in the realization I have many values that I want to change, therefore the option:
Z(1,1) = 5;
Z(2,5) = 5;
Z(4,6) = 5;
Is not an option
I'm looking for something that allows me to do it automatically, without the need for loops, if anyone knows it would help me a lot, thanks.

採用された回答

KSSV
KSSV 2020 年 6 月 2 日
編集済み: KSSV 2020 年 6 月 2 日
Read about sub2ind
Z =zeros(5,6) ;
idx = [1 1; 2 5; 4 6] ;
idx = sub2ind(size(Z),idx(:,1),idx(:,2)) ;
Z(idx) = 5

その他の回答 (1 件)

Chris Angeloni
Chris Angeloni 2020 年 6 月 2 日
編集済み: Chris Angeloni 2020 年 6 月 2 日
You probably want to get the index as a linear subscript instead of row,column, then index a vectorized version of your original matrix.
Z = zeros(5,6);
idx = [1 1; 2 5; 4 6];
% save size of Z
sz = size(Z);
% vectorize Z
Z = Z(:);
% make row,col index to linear index
lInd = sub2ind(sz,idx(:,1),idx(:,2))
Z(lInd) = 5;
% resize Z to original size
Z = reshape(Z,sz(1),sz(2));
  2 件のコメント
Alejandro Fernández
Alejandro Fernández 2020 年 6 月 2 日
Thank you very much for the answer, it works, however KSSV's answer is much smaller in terms of code.
Chris Angeloni
Chris Angeloni 2020 年 6 月 2 日
Yes, I saw it after! I forgot you can use the linear index to index the original matrix

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

カテゴリ

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

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by