A compact way to (i) sum two rows and two columns and then (ii) remove one of the two summed rows and one of the two summed columns

1 visualización (últimos 30 días)
A compact way to (i) get the sum of two rows and two columns and (ii) to then remove one of the summed rows and one of the summed columns, i.e. x3 in the example here below?
% Input 1:
x1 = [1 0 5 7 1 0
3 2 0 1 2 0
9 8 0 0 0 6
5 5 6 7 1 1
1 1 1 9 4 5
0 0 1 7 6 2]
% Input 2:
% the rows to be summed are the 2nd and the 3rd,
% while the columns to be summed are the 4th and the 5th.
x1 = 6×6
1 0 5 7 1 0 3 2 0 1 2 0 9 8 0 0 0 6 5 5 6 7 1 1 1 1 1 9 4 5 0 0 1 7 6 2
% For rows: (i) sum 2nd and 3rd rows and (ii) remove one of the two summed rows
x2 = vertcat(x1(1,:),x1(2,:)+x1(3,:),x1(4:6,:))
x2 = 5×6
1 0 5 7 1 0 12 10 0 1 2 6 5 5 6 7 1 1 1 1 1 9 4 5 0 0 1 7 6 2
% For columns: (i) sum 4th and 5th columns and (ii) remove one of the two summed columns
% --> this is the desired output
x3 = [x2(:,1:3), x2(:,4)+x2(:,5), x2(:,6)]
x3 = 5×5
1 0 5 8 0 12 10 0 3 6 5 5 6 8 1 1 1 1 13 5 0 0 1 13 2
  1 comentario
Kymberly
Kymberly el 5 de Dic. de 2022
The same stuff, but just with the "Input 2" addded in a bit more sophisticated way:
% input 1
x1 = [1 0 5 7 1 0
3 2 0 1 2 0
9 8 0 0 0 6
5 5 6 7 1 1
1 1 1 9 4 5
0 0 1 7 6 2]
x1 = 6×6
1 0 5 7 1 0 3 2 0 1 2 0 9 8 0 0 0 6 5 5 6 7 1 1 1 1 1 9 4 5 0 0 1 7 6 2
% input 2
r = 2;
c = 4;
% (i) sum 2nd and 3rd rows and (ii) remove one of the two summed rows
x2 = vertcat(x1(1:r-1,:),x1(r,:)+x1(r+1,:),x1(r+2:end,:))
x2 = 5×6
1 0 5 7 1 0 12 10 0 1 2 6 5 5 6 7 1 1 1 1 1 9 4 5 0 0 1 7 6 2
% (i) sum 4th and 5th columns and (ii) remove one of the two summed columns
x3 = [x2(:,1:c-1), x2(:,c)+x2(:,c+1), x2(:,c+2:end)]
x3 = 5×5
1 0 5 8 0 12 10 0 3 6 5 5 6 8 1 1 1 1 13 5 0 0 1 13 2

Iniciar sesión para comentar.

Respuesta aceptada

Davide Masiello
Davide Masiello el 5 de Dic. de 2022
Your way is already quite compact. Maybe what you want to avoid is having to concatenate.
Then, you could try this.
x1 = [1 0 5 7 1 0
3 2 0 1 2 0
9 8 0 0 0 6
5 5 6 7 1 1
1 1 1 9 4 5
0 0 1 7 6 2];
r = 2;
c = 4;
x1(r,:) = x1(r,:)+x1(r+1,:); x1(r+1,:) = []
x1 = 5×6
1 0 5 7 1 0 12 10 0 1 2 6 5 5 6 7 1 1 1 1 1 9 4 5 0 0 1 7 6 2
x1(:,c) = x1(:,c)+x1(:,c+1); x1(:,c+1) = []
x1 = 5×5
1 0 5 8 0 12 10 0 3 6 5 5 6 8 1 1 1 1 13 5 0 0 1 13 2

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by