如果假设为3x3x3阵列,如果满足条件,如何替换整个dim3?给出数组
A = [1 2 3; 4 1 6; 7 8 1];
A(:, :, 2) = [1 2 3; 4 2 6; 7 8 2]
A(:, :, 3) = [1 2 3; 4 3 6; 7 8 3]
在这个简单的案例中,[1 2 3]
和A(2,2,:)
上有两个包含A(3,3,:)
的dim3。我怎么能用[10 10 10]
替换它们。这看起来很简单,但我无法理解它......
编辑:我意外地过度简化了探测器,替换导体应该更像是[11 12 13]
,发现(X,Y) - 索引不是实际问题。
我正在寻找一种干净且内存有效的方法,用[11 12 13]替换A(2,2,:)
和A(3,3,:)
获取输出:
A(:,:,1)=
1 2 3
4 11 6
7 8 11
A(:,:,2) =
1 2 3
4 12 6
7 8 12
A(:,:,3) =
1 2 3
4 13 6
7 8 13
在这种情况下的原因是,我不知道在现实世界的问题中有多少要被替换掉......
答案 0 :(得分:1)
只是一些逻辑索引(Matlab 2016b及更高版本):
target = [1 2 3]; % the vector you want to find
replacement = [11 12 13]; % the vector you want to replace it with
% find the 2d indexes where the target is found
idx = all(A == permute(target,[1 3 2]),3);
% replace found indexes with replacement vector
A(logical(idx.*ones(1,1,size(A,3)))) = repelem(replacement,1,nnz(idx));
Matlab pre 2016b的相同之处:
idx = all(bsxfun(@eq,A,permute(target,[1 3 2])),3);
A(logical(bsxfun(@times,idx,ones(1,1,size(A,3))))) = repelem(replacement,1,nnz(idx));
答案 1 :(得分:0)
沿第三维更换元素只是一项任务。
A(2,2,:) = 10;
A(:,:,1) =
1 2 3
4 10 6
7 8 1
A(:,:,2) =
1 2 3
4 10 6
7 8 2
A(:,:,3) =
1 2 3
4 10 6
7 8 3
如果你想确定你在第三维度上有1,2,3模式的位置,你可以这样做:
idx= A(:,:,1) == 1 & A(:,:,2) ==2 & A(:,:,3) == 3;
idx= repmat(idx,1,1,3);
A(idx) = 10;
结果是:
A(:,:,1) =
1 2 3
4 10 6
7 8 10
A(:,:,2) =
1 2 3
4 10 6
7 8 10
A(:,:,3) =
1 2 3
4 10 6
7 8 10
答案 2 :(得分:0)
我以某种方式制定了一个基于'Aero Engy上一篇文章的解决方案然而它非常丑陋,因为它需要循环中的符号 - 有人对矢量化版本有所了解吗?
A = [1 2 3; 4 1 6; 7 8 1];
A(:, :, 2) = [1 2 3; 4 2 6; 7 8 2];
A(:, :, 3) = [1 2 3; 4 3 6; 7 8 3];
Target = [1 2 3];
Replacement = [11 12 13];
idx = find(A(:,:,1) == Target(1) & A(:,:,2) == Target(2) & A(:,:,3) == Target(3));
[x, y, ~] = ind2sub(size(A), idx);
for i = 1:length(x)
A(x(i), y(i), 1) = Replacement(1);
A(x(i), y(i), 2) = Replacement(2);
A(x(i), y(i), 3) = Replacement(3);
end