Create a Loop for this process

2 vues (au cours des 30 derniers jours)
DARLINGTON ETAJE
DARLINGTON ETAJE le 23 Juin 2021
Commenté : Stephen23 le 24 Juin 2021
I have a process which works fine. You can see the code below. I need to create a loop for the process. I need the loop to take in multiple number of c. c is usually a 3 by 3 matrix. L is usual a 1 by 12 matrix.
n=3;
c1=[12 40 13;10 11 70;80 9 1]; % C matrix for member 1
c2=[0 0 -1;0 1 0;1 0 0]; % C matrix for member 2
c3=[0 1 0;0 0 1;1 0 0]; % C matrix for member 3
L1=[13 14 15 16 17 18 1 2 3 4 5 6]; % for member 1
L2=[1 2 3 4 5 6 7 8 9 10 11 12]; % for member 2
L3=[19 20 21 22 23 24 7 8 9 10 11 12]; % for member 3
L=[L1;L2;L3];
T1=zeros(size(L1,1));
T2=zeros(size(L2,1));
T3=zeros(size(L3,1));
for i=1:n
for j=1:n
T1(i,j)=c1(i,j);
T1(i+3,j+3)=c1(i,j);
T1(i+6,j+6)=c1(i,j);
T1(i+9,j+9)=c1(i,j);
T2(i,j)=c2(i,j);
T2(i+3,j+3)=c2(i,j);
T2(i+6,j+6)=c2(i,j);
T2(i+9,j+9)=c2(i,j);
T3(i,j)=c3(i,j);
T3(i+3,j+3)=c3(i,j);
T3(i+6,j+6)=c3(i,j);
T3(i+9,j+9)=c3(i,j);
end
end
  5 commentaires
DARLINGTON ETAJE
DARLINGTON ETAJE le 24 Juin 2021
Thank you so much DGM. this is absolutely correct. I am looking for how to accept your answer...
I am grateful.
The only thing left is to find a way to create variabe names to assign each 12 by 12 matrices so I dont have 3D variables....is that even possible?
Stephen23
Stephen23 le 24 Juin 2021
"The only thing left is to find a way to create variabe names to assign each 12 by 12 matrices so I dont have 3D variables....is that even possible?"
Of course it is possible, if you want to force yourself into writing slow, complex, inefficient code that is difficult to debug:
The neat, simple, very efficient approach is to use indexing, just as DGM has already correctly advised you.

Connectez-vous pour commenter.

Réponses (1)

DGM
DGM le 24 Juin 2021
Generally, using a bunch of numbered variables is something you should try to avoid.
That said, you can make the above code into a function that will return a variable length list of T arrays for an equal-length list of C arrays.
C1 = rand(3,3);
C2 = rand(3,3);
dn = 4;
% output list length should be same as number of Cn arrays
[T1 T2] = makebdiag(dn,C1,C2)
function varargout = makebdiag(dn,varargin)
varargout = cell(size(varargin));
for n = 1:numel(varargin)
arglist = repmat(varargin(n),[1 dn]);
varargout{n} = blkdiag(arglist{:});
end
end

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by