![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1060550/image.png)
Create a matrix that changes size according to a variable N
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
wissal zaher
am 10 Jul. 2022
Kommentiert: Steven Lord
am 11 Jul. 2022
Hello,
I'm working on a project consisting of creating an MPC controller from scratch and the matrices need to be defined in a way where the size can change given a variable N (the prediction Horizon). I've already wirtten the matrices for N=7 but how can I do so for a flexible N input.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1060490/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1060495/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1060500/image.png)
The size of the Matrices is given below.
A,B,Q,R, x_min, x_max, u_min, u_max are defined as follow :
A = [1 0.1;0 1]
B = [0.005;0.1]
Q = [1 0;0 1]
R = 0.1
x_min = [-5;-5]
x_max = [5;5]
u_min = -1
u_max = 1
0 Kommentare
Akzeptierte Antwort
patrick1704
am 10 Jul. 2022
Well, one option on how to e.g. create your
is to do something like this:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1060550/image.png)
Atilde = arrayfun(@(x) A.^x, 0:1:n, 'UniformOutput',false).';
Atilde = vertcat(Atilde{:});
Similarly, you can implement other solutions for your other setups. I would recommend you to just take a look at Matlab-internal functions like: Block diagonal matrix - MATLAB blkdiag - MathWorks Deutschland, Repeat copies of array - MATLAB repmat - MathWorks Deutschland, Apply element-wise operation to two arrays with implicit expansion enabled - MATLAB bsxfun - MathWorks Deutschland, ...
Naturally, doing everything in a for-loop using if-clauses is also an option. It mainly depends on how efficient you need the implementation to be.
2 Kommentare
Steven Lord
am 11 Jul. 2022
Bor Btilde I think I have to create a loop .. any ideas ?
Create a for loop?
You may have heard that "for loops in MATLAB are slow." At one time, years ago, that may have been true. It has become less and less true as we've enhanced the language.
If for loops are the right tool for the job, use them.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!