Reputation: 45
I have N
groups of arrays. Each group contains 3 arrays for example.
Now I would like to take only one array from each of these groups and take a product with B
array.
For example:
A
3D array is given, 2x2x32
.
I split A
and get B_i
( 2 x 2 x 8), 3D array too, but i=1,..., 8
. It means B_i
is formed as a slices of A
.
Each B_i
has sub-arrays, 2 D arrays 2x2 :C_k
.
B_1(:,:,m)=C_1, where m is size( B_i, 3)
In each B_i there are 8 sub-array C_k. I am looking for an algorithm that helps me to take random one of them (one of C_k) and use it later for another computation.
How can I implement random choosing of the array in B_i?
Upvotes: 1
Views: 299
Reputation: 18177
You want a random column, with index 1, 2, 3
. Thus, don't set numel(A)
as your max integer in randi()
, instead, set it at 3
:
A = rand(2,2,3,5); % three 2-by-2 matrices, in each of 5 groups
B = rand(2,2); % Chosen for convenience; replace as warranted
% Preallocate C to have the same size as A_k * B, with as many groups
C = zeros([size(A,1),size(A,2),size(A,4)]);
for ii=1:size(A,4) % Loop over all groups/slices
% Choose a random column in {1, 2, 3} for each slice ii
C(:,:,ii) = A(:,:,randi(3),ii)*B;
end
In this example there are 5 groups (fourth dimension of A
), each group has three entries (third dimension), of 2 -by- 2 matrices (first two dimensions). Thus, loop over each group, the fourth dimension, choose a random A
matrix through randi(3)
on the third dimension, then multiply the remaining two dimensions with B
, and store in C
. C
will have the dimensions of A_k * B
, in this case chosen to be 2 -by- 2, and as third dimension the number of groups in A
.
Upvotes: 1