필터 지우기
필터 지우기

Add a value to an element in a matrix

조회 수: 9 (최근 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 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