How do I sum specific values of one matrix to another one?

1 vue (au cours des 30 derniers jours)
JOSUE PÁNCHEZ
JOSUE PÁNCHEZ le 16 Nov 2021
Modifié(e) : Image Analyst le 16 Nov 2021
If I have a square matrix A, how can I add specific values from another matrix B
A=zeros(3)
B=[1 2;3 4]
If I want to sum such us B(1,1) in A(2,2) and B(2,2) in A(3,3) how can I do it so I can get:
A=[0 0 0;
0 2 0;
0 0 4]
I've tried using indexing but it turns out to be annoying for a square matrix of 10x10

Réponse acceptée

Image Analyst
Image Analyst le 16 Nov 2021
Modifié(e) : Image Analyst le 16 Nov 2021
A=zeros(3);
B=[1 2;3 4];
A(2,2) = B(1,2);
A(3,3) = B(2,2)
A = 3×3
0 0 0 0 2 0 0 0 4
Not sure what you want to sum with a 10x10 A and/or B. Please explain with a matrix of that size.
  1 commentaire
Image Analyst
Image Analyst le 16 Nov 2021
Modifié(e) : Image Analyst le 16 Nov 2021
What exactly do you mean by "sum" and "to" in "sum specific values of one matrix to another one"? Do you mean you want to add column 2 of B to A at positions where B is shifted one row and column into A. So if A is N rows and B is (N-1) rows then you'd add the values of column 2 of B to the diagonal of A, like this:
rows = 3;
A = zeros(rows); % Any rows-by-rows square array - could be any values.
B = reshape(1:(rows-1)^2, rows-1, rows-1)' % E.g. [1 2;3 4]
B = 2×2
1 2 3 4
% Add column 2 of B, at one row more diagonally, to A.
for row = 2 : rows
A(row, row) = A(row, row) + B(row - 1, 2);
end
A % Show the final A in command window.
A = 3×3
0 0 0 0 2 0 0 0 4
Essentially this is a for loop version of Star's vectorized version.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by