Kronocker product of iteration sequence

2 次查看(过去 30 天)
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

采纳的回答

Voss
Voss 2023-12-20
编辑:Voss 2023-12-20
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Downloads 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by