在没有for循环的情况下更改矩阵的多个元素(具有已知坐标) [英] Changing multiple elements (of known coordinates) of a matrix without a for loop

查看:77
本文介绍了在没有for循环的情况下更改矩阵的多个元素(具有已知坐标)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵说

Z = [1 2 3;
     4 5 6;
     7 8 9]

我必须将其值更改为某个指定值,例如在位置(2,2)和(3,1)处.我有两个包含这些位置的矩阵rowNoscolNos:

I have to change its values, say at positions (2,2) and (3,1), to some specified value. I have two matrices rowNos and colNos which contain these positions:

rowNos = [2, 3]
colNos = [2, 1]

假设我想将这些位置的元素值更改为0.

Let's say I want to change the value of elements at these positions to 0.

如何在不使用for循环的情况下做到这一点?

How can I do it without using for loop?

推荐答案

使用 sub2ind ,它将把您的子索引转换为线性索引,线性索引是指向矩阵中一个确切位置的数字(

Use sub2ind, it'll convert your sub-indices to linear indices, which is a number pointing at one exact spot in the matrix (more info).

Z = [ 1 2 3 ; 4 5 6 ; 7 8 9];
rowNos = [2, 3];
colNos = [2, 1];

lin_idcs = sub2ind(size(Z), rowNos, colNos)

如果要对特定行和列上的所有元素(即尺寸较大的元素)进行操作,则还可以使用线性索引对其进行处理.计算它们只会变得有些棘手:

If you want to operate on all elements on a specific row and column (elements in higher dimensions that is), you can also address them using linear indexing. It only becomes a bit trickier of calculating them:

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;

使用sub2ind进行一些实验,并逐步阅读我的代码以了解它.

experiment a bit with sub2ind, and go through my code step-by-step to understand it.

如果这是您要删除所有元素的第一个维度,那会更容易,那么您可以使用冒号运算符:

It would've been easier if it was the first dimension you wanted to take all elements off, then you could have used the colon operator :

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;

这篇关于在没有for循环的情况下更改矩阵的多个元素(具有已知坐标)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆