nof*_*lly 2 matlab element permutation matrix
我有一个矩阵A.
A = [0 0 0 0 1; 0 0 0 0 2; 0 1 2 3 4];
Run Code Online (Sandbox Code Playgroud)
我想随机置换每一行中的元素.例如,矩阵A2
A2 = [1 0 0 0 0; 0 0 0 2 0; 4 1 3 2 0]; % example of desired output
Run Code Online (Sandbox Code Playgroud)
我可以用矢量做到这一点:
Av = [0 1 2 3 4];
Bv = Av(randperm(5));
Run Code Online (Sandbox Code Playgroud)
但我不确定如何在矩阵中连续执行此操作,并且仅对给定行中的元素进行置换.这可能吗?我可以从许多置换向量构造一个矩阵,但我宁愿不这样做.
谢谢.
你可以使用sort任何大小的随机数组(这是什么randperm).在那之后,你需要做的就是一些索引技巧来正确地重新调整数组
A = [0 0 0 0 1; 0 0 0 0 2; 0 1 2 3 4];
[nRows,nCols] = size(A);
[~,idx] = sort(rand(nRows,nCols),2);
%# convert column indices into linear indices
idx = (idx-1)*nRows + ndgrid(1:nRows,1:nCols);
%# rearrange A
B = A;
B(:) = B(idx)
B =
0 0 1 0 0
0 2 0 0 0
2 1 3 4 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4085 次 |
| 最近记录: |