基于向量的向量化列替换 - MATLAB
Vectorize columns replacement based on a vector - MATLAB
我想根据矢量值以矢量化方式替换矩阵第 n 列的值。
输入:
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
矢量:
[2]
[4]
[1]
[3]
预期输出:
[0 1 0 0]
[0 0 0 1]
[1 0 0 0]
[0 0 1 0]
带 for 循环的 Matlab 代码:
A = zeros(4,4);
b = [2; 4; 1; 3];
for row=1:4
A(row, b(row)) = 1;
endfor
带有 sub2ind 的 Matlab 代码:
A = zeros(4,4);
b = [2; 4; 1; 3];
c = [[1:length(b)]' b];
A(sub2ind(size(A), c(:,1), c(:,2))) = 1;
Matlab有没有更多矢量化的方式?谢谢你。
您可以使用sub2ind
的原始版本以向量化的方式解决它-
A( (b(:)-1)*size(A,1) + [1:numel(b)]' ) = 1;
工作原理: 由于 b
的元素是列索引并且 MATLAB 遵循列主索引,因此我们需要将每个这样的列索引与A
中的行数,以获取开始该列之前的元素数,即 (b(:)-1)*size(A,1)
。然后,添加相应的行索引,即 [1:numel(b)]'
为我们提供最终的线性索引,与 sub2ind
生成的索引相同。最后,使用这些线性索引对 A
进行索引,并根据问题的要求将它们设置为所有 1
。
我想根据矢量值以矢量化方式替换矩阵第 n 列的值。
输入:
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
矢量:
[2]
[4]
[1]
[3]
预期输出:
[0 1 0 0]
[0 0 0 1]
[1 0 0 0]
[0 0 1 0]
带 for 循环的 Matlab 代码:
A = zeros(4,4);
b = [2; 4; 1; 3];
for row=1:4
A(row, b(row)) = 1;
endfor
带有 sub2ind 的 Matlab 代码:
A = zeros(4,4);
b = [2; 4; 1; 3];
c = [[1:length(b)]' b];
A(sub2ind(size(A), c(:,1), c(:,2))) = 1;
Matlab有没有更多矢量化的方式?谢谢你。
您可以使用sub2ind
的原始版本以向量化的方式解决它-
A( (b(:)-1)*size(A,1) + [1:numel(b)]' ) = 1;
工作原理: 由于 b
的元素是列索引并且 MATLAB 遵循列主索引,因此我们需要将每个这样的列索引与A
中的行数,以获取开始该列之前的元素数,即 (b(:)-1)*size(A,1)
。然后,添加相应的行索引,即 [1:numel(b)]'
为我们提供最终的线性索引,与 sub2ind
生成的索引相同。最后,使用这些线性索引对 A
进行索引,并根据问题的要求将它们设置为所有 1
。