假设我们有一个array x
。我们可以找到该数组的最大值,如下所示:
maximum = max(x);
如果我有两个数组,比如说x和y,我可以使用以下命令找到包含最大值的数组
maximum_array = max(x, y);
假设此数组为y。然后,我可以通过使用带有参数y的max命令来找到最大值,就像以前使用x一样:
maximum_value = max(y);
可以使用以下紧凑的单线命令执行此两步过程:
maximum_value = max(max(x, y));
但是当我们有两个以上的数组时会发生什么呢?据我所知,max函数不允许比较两个以上的数组。因此,我必须将max用于数组对,然后在中间结果中找到max(还涉及使用其他变量)。当然,如果我有50个数组,那将是-确实是-一个tedius过程。
有没有更有效的方法?
方法1
串联column
沿着他们的矢量版本dim-2
有cat
,然后使用具有maximium值max
一起dim-2
,以获得最大。
因此,假设x
,y
并且z
要输入数组,做这样的事情-
%// Reshape all arrays to column vectors with (:) and then use cat
M = cat(2,x(:),y(:),z(:))
%// Use max along dim-2 with `max(..,[],2)` to get column vector
%// version and then reshape back to the shape of input arrays
max_array = reshape(max(M,[],2),size(x))
方法#2
您可以ndims
用来查找输入数组中的维数,然后沿着该维的维数进行连接plus 1
,最后max
沿其查找以获得最大值数组。这样可以避免所有的来回修改,从而可以提高效率和代码的紧凑性-
ndimsp1 = ndims(x)+1 %// no. of dimensions plus 1
maxarr = max(cat(ndimsp1,x,y,z),[],ndimsp1) %// concatenate and find max
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句