Add a value to an element in a matrix

17 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Operating 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