我需要在不使用循环的情况下实现以下循环。一个典型的例子是 size(pos) = [480 640 200 2]
。
注意:-确保pos(:,:,:,1)的1:size(pos,2)
值在范围内,而pos(:,:,:,2)的值在范围内1:size(pos,1)
[height width N ~] = size(pos);
output = uint8(zeros(height,width,0));
for k =1:N
prediction = uint8(zeros(height,width));
for i =1:height
for j =1:width
a = pos(i,j,k,2);
b = pos(i,j,k,1);
int_ = intensity(i,j,k); %// intensity is a height x width x N , uint8 matrix which has intensity values of an rgb image sequence of size height x width and length N
prediction(a,b) = int_;
end
end
output = cat(3,output,prediction);
end
编辑:-
正如Luis提到的那样,可能pos
有重复的值,因此prediction(a,b) = int_
可能会被覆盖。在那种情况下,我希望有一种方法来放置所有重复的值,而不是覆盖并仅保留最后一个值。
举一个例子,假设pos具有以下值,pos(12,12,3,1) = 12; pos(12,12,3,2) = 12; pos(13,13,3,1) = 12; pos(13,13,3,2) = 12; intensity(12,12,3) = 45 ; intensity(13,13,3) = 58
然后在此代码predicted(12,12)
中分配值,58
但我希望将其分配为some scalar value between 45 and 58
。
请记住 intensity is a height x width x N , uint8 matrix which has intensity values of an rgb image sequence of size height x width and length N
原始问题的答案:赋值覆盖值
可以覆盖值的事实使这一点变得棘手,因为分配的顺序就变得至关重要。为了保持您在循环中使用的分配顺序相同,我们使用size [width height N]
(不是[height width N]
),然后permute
返回:
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]);
修改后的问题的答案:将所有值平均/保持在一致的位置
在这种情况下,分配顺序并不重要,因此无需更改尺寸。使用accumarray
以平均coresponding到同一位置的所有值:
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
将是一个单元格数组,这样每个单元格都包含一个向量,该向量的所有值都对应于该位置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句