在 MATLAB 中查找矩阵子集的最大值,同时保留完整矩阵的索引
目前,我可以使用以下代码找到矩阵 C
的最大值及其索引:
[max_C, imax] = max(C(:));
[ypeak, xpeak] = ind2sub(size(C),imax(1));
让我们调用矩阵 C_sub
的子集,
我想找到C_sub
的最大值,但我还想知道该最大值在 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
.
Seems like it should be an easy problem, but it has me stumped.
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
创建
假设
C_sub
是由其中rows
和cols
是索引向量 的。将这些rows
和cols
向量保存在您可以重复使用的地方(如果您还没有这样做的话)。或者,如果
rows
和/或cols
是逻辑向量而不是索引向量,则可以使用find
,然后按上述操作。Suppose that
C_sub
was created bywhere
rows
andcols
are vectors of indices. Save thoserows
andcols
vectors somewhere you can reuse them, if you haven't already.Or if
rows
and/orcols
was a vector of logicals instead of a vector of indices, you can convert them usingfind
, and then proceed as above.如果您知道
C_sub
中最大值的索引,并且知道C_sub
在C
中的位置,您可以简单地将它们相加(并且对于 Matlab 索引减去 1)以获得相对于C
的最大值的索引。If you know the indices of the maximum in
C_sub
, and you know the position ofC_sub
withinC
, you can simply add them up (and subtract 1 for Matlab indexing) to get the indices of the maximum relative toC
.我曾经遇到过类似的问题,所以我编写了一个小实用程序来做到这一点。在文件交换中查找 Min2 和 Max2。这些工具允许您指定要搜索的给定矩阵的行和/或列的子集。
为自己做同样的事情。每当您需要 MATLAB 中的工具时,就编写它。不久之后,您就会建立一个适合您自己的特殊需求的漂亮工具箱。当然,首先查看文件交换,因为很可能您需要的内容已经写好并发布在那里。
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.
怎么样:
在该代码中,
C_sub_indices
是应用于生成C_sub
的C
的索引表达式。如果C_sub
不是C
的子矩阵(例如,如果它重新排列行或列),则此代码可能不起作用。What about:
In that code,
C_sub_indices
is the index expression applied toC
that producedC_sub
. This code may not work ifC_sub
is not a submatrix ofC
(e.g., if it rearranges the rows or columns).您还可以尝试这个脚本:
You can also try this script: