开发者

Find the maximum value of a matrix subset in MATLAB while preserving the indices of the full matrix

开发者 https://www.devze.com 2023-02-07 03:17 出处:网络
Currently, I\'m able to find the max value of a matrix C and its index with the following code: [max_C, imax] = max(C(:));

Currently, I'm able to find the max value of a matrix C and its index with the following code:

[max_C, imax] = max(C(:));
[ypeak, xpeak] = ind2sub(size(C),imax(1));

Let's call a subset of the matrix C_sub

I want to find the max value of C_sub, but I also want to know the index of that max value in C.开发者_Python百科

Seems like it should be an easy problem, but it has me stumped.

Thanks for your help!


Suppose that C_sub was created by

C_sub = C(rows,cols);

where rows and cols are vectors of indices. Save those rows and cols vectors somewhere you can reuse them, if you haven't already.

[max_C_sub, ind_C_sub] = max(C_sub(:));
[ypeak_sub, xpeak_sub] = ind2sub(size(C_sub), ind_C_sub);
xpeak = cols(xpeak_sub);
ypeak = rows(ypeak_sub);

Or if rows and/or cols was a vector of logicals instead of a vector of indices, you can convert them using find, and then proceed as above.

rows_ind = find(rows_logical);


If you know the indices of the maximum in C_sub, and you know the position of C_sub within C, you can simply add them up (and subtract 1 for Matlab indexing) to get the indices of the maximum relative to C.


I had a similar problem once, so I wrote a little utility to do this. Find Min2 and Max2 on the file exchange. These tools allow you to specify a subset of the rows and/or the columns of the given matrix to search over.

Do the same thing for yourself. Every time you need a tool in MATLAB, write it. Before long you will have built up a nice toolbox of tools tailored to your own special needs. Of course, look on the file exchange first, as there is a good chance that what you need has already been written and posted there.


What about:

mask = nan(size(C));
mask(C_sub_indices) = 1;
[max_C, imax] = max(C .* mask);

In that code, C_sub_indices is the index expression applied to C that produced C_sub. This code may not work if C_sub is not a submatrix of C (e.g., if it rearranges the rows or columns).


You can also try this script:

A=magic(5)
[x,y]=find(A==max(max(A))) %index maximum of the matrix A 
A_max=A(x,y)
[x1,y1]=find(A==min(max(A))) %index minimum of the matrix A 
A_min=A(x1,y1)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号