Kronocker product of iteration sequence

1 view (last 30 days)
Akmyrat
Akmyrat on 4 Jul 2014
Edited: Matt J on 20 Dec 2023
I have this code:
A=[1 0 0;1 1 0;0 1 0]
I=[1 0;0 1]
F2=[2 1;1 2]
for i=1:3
B=0;
for j=1:3
B=B+A(i,j);
end
if B==1;
eval(sprintf('R%d=I',i))
else B==2;
eval(sprintf('R%d=F2',i))
end
end
%% At the end I want to multiply all R1,R2,R3 answers like this: A=kron(R1,R2), B=kron(A,R3)
urgently need answer...thankssss

Accepted Answer

Voss
Voss on 20 Dec 2023
Edited: Voss on 20 Dec 2023
A=[1 0 0;1 1 0;0 1 0];
I=[1 0;0 1];
F2=[2 1;1 2];
Instead of using numbered variables R1, R2, R3, use a cell array:
[N1,N2] = size(A);
R = cell(1,N1); % 1xN1 cell array
for ii = 1:N1
B=0;
for jj=1:N2
B=B+A(ii,jj);
end
if B==1
R{ii} = I;
else
R{ii} = F2;
end
end
R{:}
ans = 2×2
1 0 0 1
ans = 2×2
2 1 1 2
ans = 2×2
1 0 0 1
And you can avoid the inner loop by using the sum function:
B = sum(A,2);
N = size(A,1);
R = cell(1,N);
for ii = 1:N
if B(ii) == 1
R{ii} = I;
else
R{ii} = F2;
end
end
R{:}
ans = 2×2
1 0 0 1
ans = 2×2
2 1 1 2
ans = 2×2
1 0 0 1
And you can avoid the outer loop by using logical indexing:
R = cell(1,size(A,1));
idx = sum(A,2) == 1;
R(idx) = {I};
R(~idx) = {F2};
R{:}
ans = 2×2
1 0 0 1
ans = 2×2
2 1 1 2
ans = 2×2
1 0 0 1
"At the end I want to multiply all R1,R2,R3 answers like this: A=kron(R1,R2), B=kron(A,R3)"
No problem; you can do that:
A=kron(R{1},R{2}); B=kron(A,R{3})
B = 8×8
2 0 1 0 0 0 0 0 0 2 0 1 0 0 0 0 1 0 2 0 0 0 0 0 0 1 0 2 0 0 0 0 0 0 0 0 2 0 1 0 0 0 0 0 0 2 0 1 0 0 0 0 1 0 2 0 0 0 0 0 0 1 0 2
A more general way:
B = R{1};
for ii = 2:numel(R)
B = kron(B,R{ii});
end
B
B = 8×8
2 0 1 0 0 0 0 0 0 2 0 1 0 0 0 0 1 0 2 0 0 0 0 0 0 1 0 2 0 0 0 0 0 0 0 0 2 0 1 0 0 0 0 0 0 2 0 1 0 0 0 0 1 0 2 0 0 0 0 0 0 1 0 2

More Answers (0)

Categories

Find more on Downloads in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!