# Finding max and min locations of a SparseMat in OpenCV

I want to find the *location* of max in a SparseMat matrix, using OpenCV libraries in C++.
I tried the following code that does not work:

int Tdim=1; int Tsize[]={2,3}; SparseMat samplesT(Tdim,Tsize,CV_32F); int el[]={1,2}; // max location samplesT.ref<float>(el)=5; // setting max value double TmaxVal, TminVal; int TmaxIdx, TminIdx; minMaxLoc(samplesT, &TminVal, &TmaxVal, &TminIdx, &TmaxIdx); cout<<"TmaxIdx= "<<(TmaxIdx)<<endl; // returns: 1 cout<<"TmaxVal= "<<(samplesT.ref<float>(TmaxIdx))<<endl; // returns: 5

It is really strange that

samplesT.ref<float>(TmaxIdx)

correctly returns the max value of the matrix, however, TmaxIdx only contains the *row* of the max value in the matrix!

I would appreciate any methods could be used to find **x** and **y** of the max value in an OpenCV SparseMat matrix.

## Answers

There are two problems. First, since Tdim equals 1, you're working with a 1D matrix instead of a 2D one, so you need to set Tdim to 2. The other problem is that TmaxIdx and TminIdx should be int arrays of length 2, not single ints (since you're looking for a 2D coordinate). With that change, you get the following:

int TmaxIdx[2], TminIdx[2]; minMaxLoc(samplesT, &TminVal, &TmaxVal, TminIdx, TmaxIdx);

Then you can verify the solution below:

fprintf(stdout, "TmaxIdx= (%d,%d)\n", TmaxIdx[0], TmaxIdx[1]); // TmaxIdx= (1, 2)