Create a loop with condition

I want to create a loop that generate random intial values x0 as (2,1) vectors within a [-5,5] range.
Each initial value x0 will give out an output U, some values give out U = NaN (calculated with a controller)
I want the loop to keep running for all the values with U not equal NaN and save them in an array Xset
The values with U = NaN can be disqualified
I would appreciate any help

 Accepted Answer

Does not seem like you need random values, but rather all values between -5 to 5
[x,y]=meshgrid(-5:.001:5);%generates all x0 pairs (x;y) within -5 to 5 with .001 step.
i=1;
for k=1:numel(x)
U=%some function with [x(k);y(k)] input
if ~isnan(U)
Xset(:,i)=[x(k);y(k)];
i=i+1;
end
end

3 Comments

Thank you for the reply, I think I should explain a bit more clearly what I meant.
I have a controller that works in a loop that takes values x0 and gives out accordingly an output u such as in the end I have a set of state Xset and respectively ouputs Uset.
as follows :
x0 = [-1;1];
T_solve=100;
Xset=x0;
Uset=[];
for k=1:T_solve
u = mpc.evaluate(x0);
x1=A*x0+B*u(1);
x0=x1;
Xset=[Xset x0];
Uset=[Uset u];
end
Now I need to check for all possible initial states x0 within the range [-5;5] and see if there is an output u before running the loop.
In the end I should generate a data set of X and U to train my neural network.
[x,y]=meshgrid(-5:.001:5);
xset=[];
for k=1:numel(x)
u = mpc.evaluate([x(k);y(k)]);
if ~any(isnan(u))
xset=[xset,k];
end
end
T_solve=100;
Xset=[];Uset=[];
for k=1:length(xset)
x0=[x(xset(k));y(xset(k))];
for kk=1:T_solve
u = mpc.evaluate(x0);
x1=A*x0+B*u(1);
x0=x1;
Xset=[Xset x0];
Uset=[Uset u];
end
end
thank you a lot !

Sign in to comment.

More Answers (0)

Categories

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

Products

Release

R2022a

Community Treasure Hunt

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

Start Hunting!