sha*_*sha 2 matlab vectorization
我有一个矩阵说
Z = [1 2 3;
4 5 6;
7 8 9]
Run Code Online (Sandbox Code Playgroud)
我必须将其值(例如位置(2,2)和(3,1))更改为某个指定值.我有两个矩阵rowNos和colNos含有这些位置:
rowNos = [2, 3]
colNos = [2, 1]
Run Code Online (Sandbox Code Playgroud)
假设我想将这些位置的元素值更改为0.
如何在不使用for循环的情况下完成它?
使用sub2ind,它会将您的子索引转换为线性索引,这是一个指向矩阵中一个精确位置的数字(更多信息).
Z = [ 1 2 3 ; 4 5 6 ; 7 8 9];
rowNos = [2, 3];
colNos = [2, 1];
lin_idcs = sub2ind(size(Z), rowNos, colNos)
Run Code Online (Sandbox Code Playgroud)
如果要对特定行和列上的所有元素(更高维度的元素)进行操作,您还可以使用线性索引来处理它们.计算它们只会变得有点棘手:
Z = reshape(1:4*4*3,[4 4 3]);
rowNos = [2, 3];
colNos = [2, 1];
siz = size(Z);
lin_idcs = sub2ind(siz, rowNos, colNos,ones(size(rowNos))); % just the first element of the remaining dimensions
lin_idcs_all = bsxfun(@plus,lin_idcs',prod(siz(1:2))*(0:prod(siz(3:end))-1)); % all of them
lin_idcs_all = lin_idcs_all(:);
Z(lin_idcs_all) = 0;
Run Code Online (Sandbox Code Playgroud)
使用sub2ind进行一些实验,并逐步完成我的代码以了解它.
如果它是你想要关闭所有元素的第一个维度会更容易,那么你可以使用冒号运算符 :
Z = reshape(1:3*4*4,[3 4 4]);
rowNos = [2, 3];
colNos = [2, 1];
siz = size(Z);
lin_idcs = sub2ind(siz(2:end),rowNos,colNos);
Z(:,lin_idcs) = 0;
Run Code Online (Sandbox Code Playgroud)