How can I remove if statement ?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Gözde Üstün
am 8 Jul. 2020
Beantwortet: Walter Roberson
am 8 Jul. 2020
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 Kommentare
Walter Roberson
am 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
Akzeptierte Antwort
Walter Roberson
am 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
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!