我需要实现以下循环而不使用循环。一个典型的例子是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
对原始问题的回答:赋值覆盖值
值可以被覆盖的事实使得这很棘手,因为赋值的顺序是至关重要的。为了保持在循环中使用的相同赋值顺序,我们使用大小为[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
对相同位置对应的所有值取平均值:
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
将是一个单元格数组,每个单元格包含一个向量,其中所有值对应于该位置。