gpt4 book ai didi

matlab - 按指定顺序创建 1 的数组

转载 作者:行者123 更新时间:2023-12-02 21:44:05 25 4
gpt4 key购买 nike

我有一个位置矩阵:

positionMatrix = [1 2 3; 1 3 2; 2 1 3];

我想要一个简单的实现(没有 for 循环),它会生成如下数组:

% there are 3 lines in positionMatrix, so it should generates 3 arrays of ones
array 1 should be [1 0 0; 0 1 0; 0 0 1] %from positionMatrix 1 2 3
array 2 should be [1 0 0; 0 0 1; 0 1 0] %from positionMatrix 1 3 2
array 3 should be [0 1 0; 1 0 0; 0 0 1] %from positionMatrix 2 1 3

positionMatrix 可以是 M x N(M 不等于 N)。

最佳答案

将输出生成为单个 3D 数组

 [M N] = size( positionMatrix );
mx = max(positionMatrix(:)); % max column index
out = zeros( [N mx M] );
out( sub2ind( size(out), ...
repmat( 1:N, [M 1] ),...
positionMatrix, ...
repmat( (1:M)', [1 N] ) ) ) = 1;
out(:,:,1) =
1 0 0
0 1 0
0 0 1
out(:,:,2) =
1 0 0
0 0 1
0 1 0
out(:,:,3) =
0 1 0
1 0 0
0 0 1

如果您希望每个输出矩阵作为不同的单元格,您可以使用mat2cell

>> mat2cell( out, N, mx, ones(1,M) )

关于matlab - 按指定顺序创建 1 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19840472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com