# Selecting a Randomly Matrix as Part of a Block Diagonal Matrix

1 view (last 30 days)
Gözde Üstün on 1 Jul 2020
Answered: Jemima Pulipati on 6 Jul 2020
Hello,
I have 2 matrix which are name temp and temp2 And I want to create a block diagonal Matrix with temp and temp2. However I want to select blocks randomly
Here is my code but I cannot run it. Is there any possibility for choosing a matrix randomly as an element of other matrix
function A = new(d)
A=zeros(d,d,2,d);
projectors_of_sigma_x = [1/sqrt(2)*[1;1],1/sqrt(2)*[1;-1]];
temp = projectors_of_sigma_x(:,1)*transpose(projectors_of_sigma_x(:,1));
temp2 = projectors_of_sigma_x(:,2)*transpose(projectors_of_sigma_x(:,2));
for k=1:d
A(:,:,1,k) = repmat(blkdiag(randi(temp,temp2),randi(temp,temp2)),1,1);
end
end

Jemima Pulipati on 6 Jul 2020
Hello,
From my understanding you are trying to use randi(temp, temp2) to randomly select between two matrices temp and temp2 but randi(imax, n) returns an n-by-n matrix of pseudorandom integers drawn from the discrete uniform distribution on the interval [1, imax]. So it is throwing an error when used with blkdiag().
You may use randperm() to generate the random permutation of positions.
You can store the temporary matrices in a cell array and then generate a random positions of matrices using randperm() and pass it on to blkdiag.
An example:
B = {temp, temp2}
order1 = randperm(2,1)
order2 = randperm(2,1)
blkdiag(B{order1}, B{order2})
order1, order2 indicate positions of matrices in B that can be passed to blkdiag()

R2020a

### Community Treasure Hunt

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

Start Hunting!

Translated by