Arrays Matlab:如何从给定代码中删除循环

Arrays Matlab:如何从给定代码中删除循环,arrays,matlab,multidimensional-array,vectorization,Arrays,Matlab,Multidimensional Array,Vectorization,我需要在不使用循环的情况下实现以下循环。 一个典型的例子是 大小(位置)=[480 640 200 2] 注意:-保证pos(:,:,:,1)的值在1:size(pos,2)范围内,而pos(:,:,:,2)的值在1:size(pos,1) 编辑:- 正如Luis所提到的,pos可能有重复的值,因此预测(a,b)=int_可能会被覆盖。在这种情况下,我希望有一种方法来放置所有重复的值,而不是覆盖并保留最后一个值 例如,假设pos具有以下值pos(12,12,3,1)=12;pos(12,12,3

我需要在不使用循环的情况下实现以下循环。 一个典型的例子是
大小(位置)=[480 640 200 2]

注意:-保证pos(:,:,:,1)的值在
1:size(pos,2)
范围内,而pos(:,:,:,2)的值在
1:size(pos,1)

编辑:-

正如Luis所提到的,
pos
可能有重复的值,因此
预测(a,b)=int_
可能会被覆盖。在这种情况下,我希望有一种方法来放置所有重复的值,而不是覆盖并保留最后一个值

例如,假设pos具有以下值
pos(12,12,3,1)=12;pos(12,12,3,2)=12;位置(13,13,3,1)=12;位置(13,13,3,2)=12;强度(12,12,3)=45;强度(13,13,3)=58
然后在这个代码中,预测(12,12)
将被赋值
58
,但我希望它被赋值为
45和58之间的一些标量值


请记住,
强度是一个高度x宽度x N,uint8矩阵,它具有大小为高度x宽度和长度N的rgb图像序列的强度值

值可以被覆盖这一事实使得这个问题变得棘手,因为赋值的顺序至关重要。为了保持循环中使用的相同分配顺序,我们使用大小
[width-height N]
(而不是
[height-width N]
),然后将
排列回:

sub3 = reshape(kron(1:N,ones(1,height*width)), [width height N]);
pos = permute(pos, [2 1 3 4]);
ind = sub2ind([width height N], pos(:,:,:,1),pos(:,:,:,2),sub3); %// linear index
output = uint8(zeros(width,height,N)); %// initiallize
output(ind) = permute(intensity, [2 1 3]); %// assign (with overwriting)
output = permute(output, [2 1 3]); %// put back into desired shape
pos = permute(pos, [2 1 3 4]);
对已编辑问题的回答:将所有值平均/保持在同一位置

在这种情况下,赋值顺序并不重要,因此不需要排列维度。用于平均与同一位置相关的所有值:

sub3 = reshape(kron(1:N,ones(1,height*width)), [height width N]);
ind = sub2ind([height width N], pos(:,:,:,2),pos(:,:,:,1),sub3); %// linear index
output = accumarray(ind(:), double(intensity(:)), [height*width*N, 1], @mean);
output = reshape(output, [height width N]);
或者,如果要保留每个位置的所有值,只需使用返回所有值的自定义匿名函数修改
accumarray
行即可:

sub3 = reshape(kron(1:N,ones(1,height*width)), [height width N]);
ind = sub2ind([height width N], pos(:,:,:,2),pos(:,:,:,1),sub3); %// linear index
output = accumarray(ind(:), double(intensity(:)), [height*width*N, 1], @(x) {x});
output = reshape(output, [height width N]);

在后一种情况下,
output
将是一个单元数组,这样每个单元都包含一个向量,该向量具有与该位置对应的所有值。

是否可能
pos
具有重复值,从而
预测(a,b)=int有时会覆盖?@LuisMendo是的,这是可能的。如果您能告诉我一种方法,使我能够将特定位置的所有重复值
a,b
合并到单个值中,而不仅仅覆盖并保留最后一个值,我将不胜感激。强度矩阵的值是rgb图像的强度值;问题就大不相同了我得到了这个错误
???在52处使用==>sub2ind时出错下标向量必须大小相同。==>使用24*行24处的跟踪强度通过位置写入图像时出错*第24行为:*ind=sub2ind([width-height N],位置(:,:,:,:,1),位置(:,:,:,2),sub3);%//线性索引
可能是因为`大小(sub3)=[width-height N]``而
大小(pos(:,:,:,:,1)=[height-width N]
起作用了。谢谢,执行时间从
60.89秒减少到了2.7秒
。你能给我一些建议来解决第二部分(编辑后的部分)吗。请参阅已编辑的问题。
accumarray
可以执行您想要的操作。我假设您希望在同一位置对所有值进行平均,或者您也可以保留所有值,而不仅仅是它们的平均值
sub3 = reshape(kron(1:N,ones(1,height*width)), [height width N]);
ind = sub2ind([height width N], pos(:,:,:,2),pos(:,:,:,1),sub3); %// linear index
output = accumarray(ind(:), double(intensity(:)), [height*width*N, 1], @(x) {x});
output = reshape(output, [height width N]);