Shifting column of a matrix with maximum sum to the right?

1 view (last 30 days)
After using a for loop to calculate the sum in each column of the matrix; how can I move the column with largest sum to the right of the matrix? I used:
for i = i: b
sum_col(i)=sum(B(:, i));
end
[I,M]=max(sum_col);
C=A(:,2);
A(:,2)=A(:,I);
A(:,I)=C;
- After using a for loop to calculate the sum

Accepted Answer

Stephen23
Stephen23 on 2 Nov 2018
Edited: Stephen23 on 2 Nov 2018
>> M = randi(9,4,7) % fake data
M =
9 5 5 1 6 9 4
3 5 8 9 1 5 2
2 1 7 8 7 4 9
7 2 8 5 2 3 5
>> sum(M,1) % sum of each column
ans =
21 13 28 23 16 21 20
>> [~,X] = max(sum(M,1)); % max column sum.
>> M = M(:,[1:X-1,X+1:end,X]) % rearrange
M =
9 5 1 6 9 4 5
3 5 9 1 5 2 8
2 1 8 7 4 9 7
7 2 5 2 3 5 8
>> sum(M,1) % check
ans =
21 13 23 16 21 20 28

More Answers (1)

madhan ravi
madhan ravi on 2 Nov 2018
Edited: madhan ravi on 2 Nov 2018
no need of loops and no need to rearrange - JUST SWAP!
>> a=rand(4)
[~,X]=(max((sum(a))))
a(:,[X end])=a(:,[end X])
a =
0.2501 0.5916 0.5017 0.6008
0.9277 0.2033 0.6508 0.1125
0.0686 0.6359 0.7960 0.5158
0.2994 0.7984 0.2334 0.8378
X =
2
a =
0.2501 0.6008 0.5017 0.5916
0.9277 0.1125 0.6508 0.2033
0.0686 0.5158 0.7960 0.6359
0.2994 0.8378 0.2334 0.7984
>>
  4 Comments
Stephen23
Stephen23 on 2 Nov 2018
Note that this changes the order of the other columns, which may or may not be acceptable.

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!