How to fill a zeros 3D array with a random number of ones specified in a 2D matrix?
1 次查看(过去 30 天)
显示 更早的评论
The 3D array A is of size MxNxP.
The 2d matrix B is of size MxN.
For each row of B, there is at maximum one element greater than zero.
Example:
B = [0 3 0; 2 0 0];
A = zeros(2,3,4);
I want to randomly fill A such that it has exactly three ones in the first row and second column and exactly two ones in the second row and first column. For instance:
A(:,:,1) = [0 1 0; 0 0 0]
A(:,:,2) = [0 1 0; 1 0 0]
A(:,:,3) = [0 0 0; 1 0 0]
A(:,:,4) = [0 1 0; 0 0 0]
In other words, the B elements indicate how many ones should be in the third dimension of A with the same row and column indices.
I am currently able to do it with a loop but I'm looking forward to do it in a more efficient way.
This is my code:
B = [0 3 0; 2 0 0];
A = zeros(2,3,4);
for i = 1:size(B,1)
[r,c] = max(B(i,:));
idx = randperm(size(A,3),r);
A(i,c,idx) = 1;
end
0 个评论
回答(1 个)
Ameer Hamza
2020-10-2
This is a one method
B = [0 3 0; 2 0 0];
n = 4;
A = zeros([size(B) n]);
idx = arrayfun(@(x) {randperm(4, x)}, B);
for i = 1:size(A, 1)
for j = 1:size(A, 2)
A(i, j, idx{i,j}) = 1;
end
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!