How can I remove if statement ?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Walter Roberson
2020-7-8
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
采纳的回答
Walter Roberson
2020-7-8
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!