How to fill a zeros 3D array with a random number of ones specified in a 2D matrix?

2 次查看(过去 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

回答(1 个)

Ameer Hamza
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
  1 个评论
Sergio Martiradonna
Thank you for your anwer. Still, as I wrote in my question I am currently able to do it with a loop but I'm looking forward to do it in a more efficient way, hence without a loop. The main reason is that M and N are really large.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by