Azzera filtri
Azzera filtri

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

2 visualizzazioni (ultimi 30 giorni)
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

Risposte (1)

Ameer Hamza
Ameer Hamza il 2 Ott 2020
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 Commento
Sergio Martiradonna
Sergio Martiradonna il 6 Ott 2020
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.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by