具有不同尺寸输入的函数的arrayfun [英] arrayfun with function with inputs of different dimensions

查看:171
本文介绍了具有不同尺寸输入的函数的arrayfun的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个包含较大nxn矩阵的kxk子矩阵的平均值的矩阵,其中n可被k整除.我可以通过这样的方式相当有效地完成此任务

I'm trying to create a matrix that contains the averages of the kxk submatrices of a larger nxn matrix, where n is divisible by k. I can accomplish this fairly efficiently with something like this

mat = mat2cell(mat, k*ones(1,n/k), k*ones(1,n/k))
mat = cellfun(@mean,mat,'UniformOutput',false);
mat = cellfun(@mean,mat,'UniformOutput',false); %repeated to collapse cells to 1x1
mat = cell2mat(mat)

但是,由于我的数据量很大,而且矩阵很大,因此即使在群集上重复执行此过程仍会花费很长时间,并且由于内存限制,合并矩阵也不是一种选择.我想知道是否可以使用arrayfun重写此代码,以便我可以利用其GPU功能(因为GPU无法处理单元阵列),但是由于助手功能,我遇到了问题

However, since I have a very large amount of data all in very large matrices, repeating this process can still take a long time even on a cluster, and combining the matrices is not an option due to memory limitations. I'm wondering if it's possible to rewrite this code using arrayfun instead so I can utilize its GPU capability (as GPU cannot process cell arrays), but I'm running into problems since the helper function

function avg = blockavg(mat,i,j,k)
i1 = (i-1)*k+1;
i2 = i*k;
j1 = (j-1)*k+1;
j2 = j*k
avg = mean(mean(mat(i1:i2,j1:j2)));
end

调用两个广播变量mat(一个nxn矩阵)和k一个标量,当插入arrayfun时,它们不是数组输入.跑步时

calls for two broadcast variables mat, an nxn matrix, and k, a scalar, and these are not array inputs when plugged into arrayfun. When running

ii = 1:(n/k);
jj = 1:(n/k);
matavg = arrayfun(@blockavg,mat,ii,jj,k)

返回一条错误消息,指出输入参数必须是相同大小和形状的数组,因为只有iijj是数组输入,而matk不会在元素之间变化.我不太确定如何解决此问题,或者即使arrayfun完全可以进行这种类型的操作,我也不确定.任何建议表示赞赏.

An error message returns stating that input arguments must be arrays of the same size and shape, as only ii and jj are the array inputs, while mat and k do not vary across elements. I'm not quite sure how to work around this issue, or even if this type of operation is possible at all for arrayfun. Any suggestion is appreciated.

谢谢!

推荐答案

不使用图像处理工具箱的另一种可能性:

Another nice possibility without using the image processing toolbox:

squeeze(mean(mean(reshape(X,k,n/k,k,n/k),1),3))

此代码以某种方式重塑矩阵,使得每个块都可以通过Y(a,:,b,:)进行访问,这意味着它们具有相同的一维和三维索引.然后将均值应用于第一维和第三维,最后除去单例维,以获得二维结果.

This code reshapes the matrix in a way, that each block can be accessed by Y(a,:,b,:), which means they have identical first and third dimension index. Then mean is applied to first and third dimension, finally singleton dimensions are removed to get a 2d-result.

这篇关于具有不同尺寸输入的函数的arrayfun的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆