필터 지우기
필터 지우기

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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by