Creating a matrix with results of while loop
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Albert Taylor
il 31 Mar 2019
Commentato: Geoff Hayes
il 1 Apr 2019
Hi i'm new to MATLAB and was wondering how to plot a two column matrix, one column contianing the count number and the other containing the corresponding uk1 value at each count. Any help would be much appreciated.
% 1)Randomise initial U, m
Uk0 = rand( 6 , 1 );
% 2)initialise iteration process
Uk1 = 1;
Uki = Uk0;
% 3)Begin iterative process
count = 0 ;
while abs( Uk1 - Uki ) > 10^-9
count = count + 1 ;
Uk1 = inv(Kd) * ( -Kslsu * Uk0 + f ) ;
Uki = Uk0 ;
Uk0 = Uk1 ;
end
0 Commenti
Risposta accettata
Geoff Hayes
il 31 Mar 2019
Albert - if you just want to keep track of the Uk1 from each iteration of the loop, then you could do something like
count = 0 ;
Uk1 = 1;
while abs( Uk1(end) - Uki ) > 10^-9
count = count + 1 ;
Uk1(count) = inv(Kd) * ( -Kslsu * Uk0 + f ) ;
Uki = Uk0 ;
Uk0 = Uk1(count);
end
You could pre-size the Uk1 array if you know the maximum number of iterations allowed for the while loop....so that you don't get stuck. For example,
maxIterations = 100;
count = 1 ;
Uk1 = zeros(maxIterations, 1);
Uk1(1) = 1;
while abs( Uk1(count) - Uki ) > 10^-9 && count <= maxIterations
Uk1(count) = inv(Kd) * ( -Kslsu * Uk0 + f ) ;
Uki = Uk0 ;
Uk0 = Uk1(count);
count = count + 1 ;
end
6 Commenti
Geoff Hayes
il 1 Apr 2019
If always 6x1, you could do
maxIterations = 100;
count = 1 ;
Uk1 = zeros(6, maxIterations);
Uk1(:,1) = 1;
while abs( Uk1(:,count) - Uki ) > 10^-9 && count <= maxIterations
Uk1(:,count) = inv(Kd) * ( -Kslsu * Uk0 + f ) ;
Uki = Uk0 ;
Uk0 = Uk1(:, count);
count = count + 1 ;
end
Note that you might want to adjust your condition
abs( Uk1(:,count) - Uki ) > 10^-9
since the result of the subtraction is a 6x1 array too.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!