Add a value to an element in a matrix

30 ビュー (過去 30 日間)
luca
luca 2019 年 9 月 9 日
コメント済み: luca 2019 年 9 月 9 日
Hi,
Given the following matix
D=[1 2 3 4 5 6 7 8]
A(1:length(D),1:10) = 110
S= [0 0 8 0 0 8 0 0; 0 0 0 5 0 0 0 0];
I want to add the value different from 0 in S, to a specif location in A.
A =
110 110 110 110 110 110 110 110 110 110
110 110 110 110 110 110 110 110 110 110
110 110 110 110 110 110 110 110 110 110
110 110 110 110 110 110 110 110 110 110
110 110 110 110 110 110 110 110 110 110
110 110 110 110 110 110 110 110 110 110
110 110 110 110 110 110 110 110 110 110
110 110 110 110 110 110 110 110 110 110
In particular, the value 8 must be added in the 6th column of A, while the value 5 must be added to the second column of A.
To understand in which raw to allocate the element, it depend on the position in S.
1) In this case the first 8 is in position (1,3) so must be allocated in A(3,6): 3 because it's in position 3 and 6 because all the values different from zero of the first raw of S must be added in the 6th column of A
2) The second 8 is in position (1,6) so must be allocated in A(6,6)
3) The first 5 is in position S(2,4) so must be allocated in A(4,2): 4 because it's in position 4 and 2 because all the values different from zero of the 2 raw of S must be added in the 2th column of A
Finally i want to obtain
A =
110 110 110 110 110 110 110 110 110 110
110 110 110 110 110 110 110 110 110 110
110 110 110 110 110 118 110 110 110 110
110 115 110 110 110 110 110 110 110 110
110 110 110 110 110 110 110 110 110 110
110 110 110 110 110 110 110 110 110 110
110 110 110 110 110 118 110 110 110 110
110 110 110 110 110 110 110 110 110 110
  2 件のコメント
Guillaume
Guillaume 2019 年 9 月 9 日
Why do the non-zero values is S(:, 1) go to column 6 and those in S(:, 2) go to column 2? There doesn't seem to be any logic to that. Which column would non-zeros in the 3rd row of S end up in?
luca
luca 2019 年 9 月 9 日
Cause is a specific problem where I need to add that values of S just in these columns of A

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

採用された回答

Guillaume
Guillaume 2019 年 9 月 9 日
Cause is a specific problem where I need to add that values of S just in these columns of A
Then, this should work:
A(S(1, :) ~= 0, 6) = nonzeros(S(1, :));
A(S(2, :) ~= 0, 2) = nonzeros(S(2, :));
Of course, if there were more rows in S a completely different approach would be better, but for just 2 rows this will do.
  4 件のコメント
Guillaume
Guillaume 2019 年 9 月 9 日
Yes, it is ok. But why didn't you try?
luca
luca 2019 年 9 月 9 日
I tried. I've just reported in case someone else is interested in the topic.
Thanks Guillaume

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by