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

조회 수: 5 (최근 30일)
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
Kymberly
Kymberly 2022년 12월 5일
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

댓글을 달려면 로그인하십시오.

채택된 답변

Davide Masiello
Davide Masiello 2022년 12월 5일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by