user1218247
user1218247

Reputation:

Find column index for column with smallest sum in Matlab

I have a [3 x 3] matrix in Matlab. I want to know for which column the sum of all its elements is the smallest. So specifically, i want to know what the index number is of that column.

I am thinking of doing this with a while loop, but is there a faster (or better) way?


What i'm doing right now is:

columnSum = sum(matrix,2);
minColumn = min(columnSum);

smallestColumn = 0;
columnNumber = 1;

while currentSum ~= minColumn
  smallestColumn = columnNumber;
  currentSum = columnSum(columnNumber);
  columnNumber = columnNumber + 1;
end

Upvotes: 1

Views: 1037

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78364

If your matrix is called a then this should do what you want:

[C,I] = min(sum(a,1))

I'm leaving the office now, so won't explain further, you should be able to figure it out.

Upvotes: 2

Related Questions