Creating a matrix with results of while loop

4 views (last 30 days)
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

Accepted Answer

Geoff Hayes
Geoff Hayes on 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 Comments
Albert Taylor
Albert Taylor on 1 Apr 2019
I wish to keep the 6*1 for each iteration
Geoff Hayes
Geoff Hayes on 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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!