Add a value to an element in a matrix

17 visualizzazioni (ultimi 30 giorni)
luca
luca il 9 Set 2019
Commentato: luca il 9 Set 2019
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 Commenti
Guillaume
Guillaume il 9 Set 2019
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 il 9 Set 2019
Cause is a specific problem where I need to add that values of S just in these columns of A

Accedi per commentare.

Risposta accettata

Guillaume
Guillaume il 9 Set 2019
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 Commenti
Guillaume
Guillaume il 9 Set 2019
Yes, it is ok. But why didn't you try?
luca
luca il 9 Set 2019
I tried. I've just reported in case someone else is interested in the topic.
Thanks Guillaume

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Operating on Diagonal Matrices in Help Center e File Exchange

Prodotti


Release

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by