フィルターのクリア

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

2 ビュー (過去 30 日間)
Sergio Martiradonna
Sergio Martiradonna 2020 年 10 月 2 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by