Creating a matrix with results of while loop

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

 채택된 답변

Geoff Hayes
Geoff Hayes 2019년 3월 31일

0 개 추천

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

Hey Geoff
Thanks for the help, however when implementing the first code you have given me matlab displays an error message. Is there anyway to get around this.
Unable to perform assignment because the left and right sides have a different number of elements.
Albert - presumably the error is with the line of code
Uk1(count) = inv(Kd) * ( -Kslsu * Uk0 + f ) ;
If that is the case, then the problem may be because
inv(Kd) * ( -Kslsu * Uk0 + f )
is not a scalar and so is an array of two or more elements. Can you confirm that? And if so, does that make sense?
Albert's answer moved here
Hey Geoff, thanks again for the reply
inv(Kd) * ( -Kslsu * Uk0 + f )
Is a 6*1 matrix. Is there anyway to fix this ?
Albert - it depends how you want to fix this. Should this be a scalar or do you want to keep the 6x1 from each iteration?
I wish to keep the 6*1 for each iteration
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

제품

릴리스

R2018a

질문:

2019년 3월 31일

댓글:

2019년 4월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by