MAX value of matrix and saving indexes in the same loop

maximum absolute difference of value and index sums
find index of max value in array matlab
matrix indexing
find location of max value in matrix? - matlab
finding index of maximum matlab
matlab find max of entire matrix
index of max value in a vector matlab
problem 1702 maximum value in a matrix

I get a NxM sized matrix and I have to find the max value, the number of max values and the lines that contain it. I tired using three for{for{}} loops, but it took too long. This method seems to work for small inputs, but when I try it with a 1000x1000 matrix, it finishes before it even takes all the input. I realise this may be too much of a noob question, but I couldn't find anything else.

Here's my code:

#include <iostream>
using namespace std;

int main()
{
    int n, m;
    int crnt{-51}, cnt{0};
    cin >> n >> m;
    int vekt[m];
    int lines[n];
    int inp;
    for(int i=0; i<n; i++)
    {
        for(int p=0; p<m; p++)
        {
            cin >> vekt[p];
        }
        for(int j=0; j<m; j++)
        {
            if(vekt[j] == crnt)
            {
                lines[cnt] = i + 1;
                cnt += 1;
            }
            if(vekt[j] > crnt)
            {
                crnt = vekt[j];
                lines[0] = i + 1;
                cnt = 1;
            }
        }
    }
    cout << cnt;
    for(int i=0; i<cnt; i++)
    {
        cout << " " << lines[i]; 
    }
    return 0;
}

EDIT : not using vector or [n] was just easier... I simply saved it to a variable and used a bool:

int main()
{
    int n, m;
    int crnt{-51}, cnt{0};
    cin >> n >> m;
    int vekt[m];
    int lines[n];
    int inp;
    bool inLine;
    inLine = false;
    for(int i=0; i<n; i++)
    {

        inLine = false;
        for(int j=0; j<m; j++)
        {
            cin >> inp;
            if(inp == crnt && inLine == false)
            {
                lines[cnt] = i + 1;    
                cnt += 1;
                inLine = true;    
            }
            if(inp > crnt)
            {
                crnt = inp;
                lines[0] = i + 1;
                cnt = 1;
            }
        }
    }
    cout << cnt;
    for(int i=0; i<cnt; i++)
    {
        cout << " " << lines[i]; 
    }
    return 0;
}

This cut the time by enough so that I went under the limit.

MAX value of matrix and saving indexes in the same loop, MAX value of matrix and saving indexes in the same loop - c++. I simply saved it to a variable and used a bool: int main() { int n, m; int crnt{-51}, cnt{0}; cin >> n  How to save the values after each iteration in a Learn more about values, iteration, loop, matrix, saving, nx1

Check this realization, without STL and vectors:

 void input_matrix(int **&matrix, int &lines, int &columns)
 {
     int m = 0, n = 0;
     cout << "input lines count:";
     cin >> m;
     cout << "input rows count:";
     cin >> n;

     matrix = new int *[m];
     for(int i = 0;i < m;i++)
         matrix[i] = new int[n];

     cout << endl << "input matrix:" << endl;

     for(int i = 0; i < m; i++)
         for(int j = 0; j < n; j++)
             cin >> matrix[i][j];

     lines = m;
     columns = n;
 }
 void print_matrix(int **&matrix, int &lines, int &columns)
 {
     for(int i = 0; i < lines; i++)
     {
         for(int j = 0; j < columns; j++)
             cout << matrix[i][j] << " ";
         cout << endl;
     }
 }


 int find_max(int **matrix, int lines, int columns, int &max_count)
 {
     int max = INT_MIN;
     max_count = 0;
     for(int i = 0; i < lines; i++)
         for(int j = 0; j < columns; j++)
         {
             if(matrix[i][j] > max)
             {
                 max = matrix[i][j];
                 max_count = 1;
             }
             else
                if(matrix[i][j] == max)
                    ++max_count;
         }
     return max;
 }


int main()
{
    int **matrix = nullptr;
    int m=0, n=0, count=0;
    input_matrix(matrix, n, m);
    cout << endl;
    print_matrix(matrix, n, m);
    cout << endl;
    int max = find_max(matrix, n, m, count);
    cout << "max=" << max << " count=" << count << endl;
    for(int i = 0; i < n; i++)
        delete[]matrix[i];
    delete []matrix;
}

As requested by mister Max Langhof I would also like to propose a more modern solution, based on the std::vector container, which does not need pointers and manual memory management. It's a simple class matrix:

#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdint>

using namespace std;

 class matrix
 {
 private:
     vector<vector<int>>    m_data;
 public:
     matrix(int cols, int rows)
     {
         m_data.resize(cols);
         for(auto &r : m_data)
             r.resize(rows);
     }

     int max_element()
     {
         int max = INT_MIN;
         for(auto &row: m_data)
         {
             auto maxinrow = *std::max_element(row.begin(), row.end());
             if(maxinrow > max)
                 max = maxinrow;
         }
         return max;
     }
     int element_count(int elem)
     {
         int count = 0;
         for(auto &row : m_data)
             count += std::count_if(row.begin(), row.end(), [elem](int a){return a == elem;});
         return count;
     }

     friend istream& operator>>(istream &os, matrix &matr);
     friend ostream& operator<<(ostream &os, matrix &matr);
 };

Input and output operators could be realized like this:

 istream& operator>>(istream &os, matrix &matr)
 {
     for(int i = 0; i < matr.m_data.size(); i++)
     {
         for(int j = 0; j < matr.m_data[i].size(); j++)
             cin >> matr.m_data[i][j];
         cout << endl;
     }
     return os;
 }
 ostream& operator<<(ostream &os, matrix &matr)
 {
     for(int i = 0; i < matr.m_data.size(); i++)
     {
         for(int j = 0; j < matr.m_data[i].size(); j++)
             cout << matr.m_data[i][j] << " ";
         cout << endl;
     }
     return os;
 }

And a sample of using of this matrix:

int main()
{
    int m = 5, n = 4;
    matrix matr(m, n);
    cout << "input matrix:" << endl;
    cin >> matr;
    cout << endl << matr;
    int max = matr.max_element();
    cout << "max: " << max << " count:" << matr.element_count(max) << endl;
}

How do I find the indices of the maximum (or minimum) value of my , Learn more about maximum, minimum, max, min, index, array, matrix, find, location, deep learning vs. machine learning MATLAB. I got two indices, both have the same value. Save this as a function in your base folder and use it. The integer is the "New number" that identifies the minimum, to be used for the next loop. Note that there can be the max value at more than one location. To get the rows and columns (instead of linear indexes), you can use ind2subs() or find():

Checkout something like this

#include <iostream>
#include <set>
#include <vector>

int main() {
int rowsNo, columnsNo;
std::cin >> rowsNo >> columnsNo;
std::vector<int> matrix(rowsNo*columnsNo);

//Creating matrix
for(auto row = 0; row < rowsNo; ++row) {
    for (auto column = 0; column < columnsNo; ++column)
        std::cin >> matrix[row*columnsNo + column];
}
auto maxValue = -51;
//Finding positions of maximums
std::set<int> linesWithMaxValue;
for (auto position = 0; position < matrix.size(); ++position) {
    if(matrix[position] == maxValue) 
        linesWithMaxValue.insert(position / columnsNo);
    else if(matrix[position] > maxValue) {
        linesWithMaxValue.clear();
        maxValue = matrix[position];
        linesWithMaxValue.insert(position / columnsNo);
    }
}

//Print info
const auto numberOfMaxValues = linesWithMaxValue.size();
std::cout << "Number of maxiums: " << numberOfMaxValues << std::endl;
std::cout << "Lines that contains maximum:";
for (const auto& lineId : linesWithMaxValue)
    std::cout << " " << lineId;

    return 0;
}

Finding the position of the 1st,2nd and 3rd max value in a matrix , Finding the position of the 1st,2nd and 3rd max value in a matrix My ind2sub() command returns the row/column index from the linear index returned by find(). in a loop before I'd consider the (simpler) sort() method to be too inefficient. Find max value in complete 2D numpy array. To find maximum value from complete 2D numpy array we will not pass axis in numpy.amax() i.e. # Get the maximum value from complete 2D numpy array maxValue = numpy.amax(arr2D) It will return the maximum value from complete 2D numpy arrays i.e. in all rows and columns. 17 Find max values along the axis

Artificial Neural Networks and Machine Learning, If Wmax or Wmin includes more than one index whose associated variables are use W, the first Cholesky arg max factorization F ̃i then in calculating F ̄i (14). of the originally factorized matrix, this process is sped up by storing the original and One-Cycle Loops According to [4], cyclic loops, which consist of the same​  The 'find' command only returns the indices of all the non-zero elements of a matrix. I would like to know how to find the indices of just the maximum (or minimum) value.

Computational Science, save B(is:ie,j) and E(is:ie,j) to VRs vm1 and vm2 do l = 1, k store C(l,j) and F(l,j) to scalars The search of the pivot element and exchange of matrix rows is not very costly. the search for the maximum value in the pivot column using Fortran's intrinsic function maxval and then looping until the correct index has been found  Well, every time through this loop we have overwritten the value of Y so we lost, like for instance, 9.528 when we generated 10.857. That isn't going to do very well if we want to plot this data. So what we can do is come in here and say I want to make Y into a vector.

Numerical Methods in Matrix Computations, Show how Ax = b can be solved without storing the multipliers by computing Use the function [y,i] = max(x), which returns the maximum value y and its index i​  Indexing Values in a Matrix in Matlab SnugglyHappyMathTime. Using a For Loop to Access Array Values - Duration: Using Sum, Min, Max and Find in Matlab - Duration: 4:32.

Comments
  • instead of using vector or [n], I simply saved the current input to a variable
  • int **&matrix is one hair away from Three Star Programming... And unnecessary manual resource management (i.e. new/delete) is not modern C++. What if you don't have enough memory for the last new?
  • @MaxLanghof This "old-school" style is from OP's sample. I don't think that he really needs to use STL in task like this. So many "programmers" have starting with ready containers, stl, boost and so on...and don't understand simple low-level constructions like pointers, references, new/delete..