Add a value to an element in a matrix
12 次查看(过去 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
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?
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!