How can I remove if statement ?

2 views (last 30 days)
Hello
My idea is easy; d is the dimension and I want to create a block diagonal matrix with size d from the reuslt of 2*2
I have this code but it has too many if structure but I could not write it better and it seems too ugly And idea for better code?
function [A,B] = newCHSH(d)
A=zeros(d,d,2,d);
x = [0,1;1,0];
z = [1,0;0,-1];
[xv1,xv2] = eig(x);
xv1 = [xv1(:,2),xv1(:,1)];
temp = xv1(:,1)*transpose(xv1(:,1));
temp2 = xv1(:,2)*transpose(xv1(:,2));
[zv1,zv2] = eig(z);
zv1 = [zv1(:,2),zv1(:,1)];
temp3 = zv1(:,1)*transpose(zv1(:,1));
temp4 = zv1(:,2)*transpose(zv1(:,2));
if d==2
A(:,:,1,1)=xv1(:,1)*transpose(xv1(:,1));
A(:,:,1,2)=xv1(:,2)*transpose(xv1(:,2));
A(:,:,2,1)=zv1(:,1)*transpose(zv1(:,1));
A(:,:,2,2)=zv1(:,2)*transpose(zv1(:,2));
else
if d==4
A(:,:,1,1) = blkdiag(temp,temp);
A(:,:,1,2) = blkdiag(temp2,temp2);
A(:,:,2,1) = blkdiag(temp3,temp3);
A(:,:,2,2) = blkdiag(temp4,temp4);
end
if d==6
A(:,:,1,1) = blkdiag(temp,temp,temp);
A(:,:,1,2) = blkdiag(temp2,temp2,temp2);
A(:,:,2,1) = blkdiag(temp3,temp3,temp3);
A(:,:,2,2) = blkdiag(temp4,temp4,temp4);
end
end
end
  2 Comments
Walter Roberson
Walter Roberson on 8 Jul 2020
if d == 2 || d == 4 || d == 6
repeats = d/2;
t = repmat({temp}, 1, repeats );
A(:,:,1,1) = blkdiag(t{:});
and so on, using repmat and cell expansion
end
Gözde Üstün
Gözde Üstün on 8 Jul 2020
Perfect ! Thank you very much if you write this comment as an answer, I will accept that

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 8 Jul 2020
if d == 2 || d == 4 || d == 6
repeats = d/2;
t = repmat({temp}, 1, repeats );
A(:,:,1,1) = blkdiag(t{:});
and so on, using repmat and cell expansion
end

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!