更新矩阵,每行单列,其中行索引在 vecor 中 [英] Update matrix, single column per row where row index is in vecor
问题描述
有没有办法更新矩阵每一行中的不同列,其中行索引存储在向量中.
Is there a way to update different column in each row of matrix, where row indices are stored in vector.
示例
mx = zeros(10,10);
cols = [2 3 5 4 6 8 9 1 2 3]';
for i = 1:size(mx,1)
mx(i,cols(i)) = 1;
end
mx
生产
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
问题是,我能不能不用 for 循环?
The question is, whether I can do it without the for loop?
推荐答案
您可以使用单个数字对矩阵中的元素进行寻址.在这种情况下,元素按列编号(1-10 是第一列,11-20 是第二列......)并且有一个函数 sub2ind
可以为您计算元素编号.在您的情况下,它非常简单,因为它是 10x10,因此您可以手动完成,但我仍然会推荐该功能.
You can address elements in a matrix with a single number. In this case the elements are numbered columnwise (1-10 is the first column, 11-20 the secound...) and there is a function sub2ind
to calculate the element number for you. In your case its pretty easy, because its a 10x10 so you could do it manually, but i would still recommend the function.
mx = zeros(10,10);
rows = 1:size(mx,1); %create the row indices
cols = [2 3 5 4 6 8 9 1 2 3];
X=sub2ind(size(mx),rows,cols)
mx(X)=1;
mx
这篇关于更新矩阵,每行单列,其中行索引在 vecor 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!