简体   繁体   English

matlab最大的未知维度的数组

[英]matlab maximum of array with unknown dimension

I would like to compute the maximum and, more importantly, its coordinates of an N-by-N...by-N array, without specifying its dimensions. 我想计算最大值,更重要的是,计算N-by-N ... by-N数组的坐标,而不指定其尺寸。

For example, let's take: 例如,我们采取:

A = [2 3];
B = [2 3; 3 4];

The function (lets call it MAXI ) should return the following values for matrix A : 函数(让我们称之为MAXI )应返回矩阵A的以下值:

[fmax, coor] = MAXI(A)

fmax =
   3

coor =
   2

and for matrix B : 对于矩阵B

[fmax, coor] = MAXI(B)

fmax =
    4

coor=
    2   2

The main problem is not to develop a code that works for one class in particular, but to develop a code that as quickly as possible works for any input (with higher dimensions). 主要问题不是开发一个特别适用于某个类的代码,而是开发一个尽可能快地适用于任何输入(具有更高维度)的代码。

To find the absolute maximum, you'll have to convert your input matrix into a column vector first and find the linear index of the greatest element, and then convert it to the coordinates with ind2sub . 要找到绝对最大值,您必须先将输入矩阵转换为列向量,然后找到最大元素的线性索引,然后将其转换为ind2sub的坐标。 This can be a little bit tricky though, because ind2sub requires specifying a known number of output variables. 这可能有点棘手,因为ind2sub需要指定已知数量的输出变量。 For that purpose we can employ cell arrays and comma-separated lists , like so: 为此,我们可以使用单元格数组和逗号分隔列表 ,如下所示:

[fmax, coor] = max(A(:));
if ismatrix(A)
    C = cell(1:ndims(A));
    [C{:}] = ind2sub(size(A), coor);
    coor = cell2mat(C);
end

EDIT: I've added an additional if statement that checks if the input is a matrix or a vector, and in case of the latter it returns the linear index itself as is. 编辑:我添加了一个额外的if语句,用于检查输入是矩阵还是向量,如果是后者,则返回线性索引本身。

In a function, it looks like so: 在函数中,它看起来像这样:

function [fmax, coor] = maxi(x)
    [fmax, coor] = max(A(:));
    if ismatrix(A)
        C = cell(1:ndims(A));
        [C{:}] = ind2sub(size(A), coor);
        coor = cell2mat(C);
    end

Example

A = [2 3; 3 4];
[fmax, coor] = maxi(A)

fmax =
    4

coor =
    2    2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM