Optimization of for loop to generate matrix

1 vue (au cours des 30 derniers jours)
Florian M. Faessler
Florian M. Faessler le 20 Mai 2012
Hallo, I am solving a problem in model predictive control, where I need to create two new matrices H and S out of 3 given matrices A (diemension: 2x2), B (2x1) and C (1x2). Where
S=[C*A^9; C*A^9; …; C*A] (9x2)
and
H=[C*A^7*B C*A^8*B; C*A^7*B C*A^8*B; …; 0 C*B] (9x2).
Note that the size of the resulting matrices is given by other parameters. In order to accomplish the computation I used the following code:
T=0.1; %sampling interval
A=[1 (1-exp(-T)); 0 exp(-T)]; %creating A,B,C
B=[(T-1+exp(-T)); (1-exp(-T))];
C=[1 0];
H=zeros(9,2); %defining H and S
S=zeros(9,2);
for kk=1:9 %for loop to fill H and S
H(10-kk,:)=[C*(A^kk)];
S(10-kk,:)=[C*A^(kk-2)*B C*A^(kk-1)*B];
end
S(9,1)=0;
This is working in this particular case. I started to wonder, however, if there is a more elegant way to do this. Firstly I would like to set all entries of the matrix H where kk-2<0 equal to zero and secondly I searched for a better way then using kk-10 in order to reverse the entries of the matrix when creating it.
I spent already quiet a while to search the web for some ideas. Maybe some of you have a hint for me.
Thank you! Florian

Réponses (1)

Andrei Bobrov
Andrei Bobrov le 20 Mai 2012
sh = arrayfun(@(ii)C*A^ii,(9:-1:0).','un',0)
H = cat(1,sh{1:end-1})
S0 = [cellfun(@(x)x*B,sh(2:end));0]
S = S0(bsxfun(@minus,(1:9)+1,(0:1)')')

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by