필터 지우기
필터 지우기

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
Sergio Martiradonna 2020년 10월 6일
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