How can I remove if statement ?

1 回表示 (過去 30 日間)
Gözde Üstün
Gözde Üstün 2020 年 7 月 8 日
回答済み: Walter Roberson 2020 年 7 月 8 日
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
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
Gözde Üstün
Gözde Üstün 2020 年 7 月 8 日
Perfect ! Thank you very much if you write this comment as an answer, I will accept that

サインインしてコメントする。

採用された回答

Walter Roberson
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 件)

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by