Prateek Daniels
Prateek Daniels

Reputation: 483

Find minimum across rows and count the total number of minimums across each column in Matlab

I need to initially find the minimum value across each row, amongst Column_A, Column_B and Column_C and then get the total count of the minimum values found under each of those columns in Matlab. For example, the table is as follows:

Column_A = [1.5;200;300;-1.5;49];
Column_B = [100.5;2;1;0;1];
Column_C= [1.25;500;3;0.01;200];
T = table(Column_A,Column_B,Column_C)

The table (T) with the minimum value across each row under Column_A, Column_B and Column_C are highlighted in orange:

enter image description here

I am looking to create the following output, which shows the total count of the minimum values under Column_A, Column_B and Column_C:

enter image description here

Upvotes: 2

Views: 160

Answers (2)

Rotem
Rotem

Reputation: 32144

You may apply the following solution:

  • Convert table T to numerical matrix.
  • Find the index of the minimum across rows.
  • Count number of elements of each index using histcounts.
  • Build a new table in desired format.

Here is the code:

% Build sample input:
Column_A = [1.5;200;300;-1.5;49];
Column_B = [100.5;2;1;0;1];
Column_C= [1.25;500;3;0.01;200];
T = table(Column_A,Column_B,Column_C);

% Convert T to matrix
A = T{:, :};

% Find minimum across rows, and the index of the minimum:
% You may ignore M: [~, I] = min(A, [], 2);
[M, I] = min(A, [], 2); % M = [1.25, 2, 1, -1.5, 1]', and I = [3, 2, 2, 1, 2]

% Compute total count of the minimum values under each column, by collecting histogram:
Minimum_Count = (histcounts(I, size(A, 2)))';

% Build output table:
Columns = T.Properties.VariableNames'; % Get columns names from T
T2 = table(Columns, Minimum_Count);

Result:

T2 =

  3×2 table

     Columns      Minimum_Count
    __________    _____________

    'Column_A'          1      
    'Column_B'          3      
    'Column_C'          1      

Upvotes: 2

Burak
Burak

Reputation: 2495

Column_A = [1.5; 200; 300; -1.5; 49];
Column_B = [100.5; 2; 1; 0; 1];
Column_C = [1.25; 500; 3; 0.01; 200];

% create matrix
M = [Column_A, Column_B, Column_C];

% find min in each row
min_values = min(M, [], 2) == M;
count_T = sum(min_values);

% create table
Columns = ['Column_A'; 'Column_B'; 'Column_C'];
T = table(Columns, count_T');
T.Properties.VariableNames([2]) = {'Minimum Count'};
disp(T)

Upvotes: 2

Related Questions