I'm using a for loop to create a new random variable X with range [0 1], I want the forloop to ignore values above 1 and iterate untill all the values are in range.
Mostrar comentarios más antiguos
clc; clear all; close all;
n = 200; % Number of iteration
ro = 0.75; % Correlation factor
X = zeros(1,n);
x = zeros(1,n);
for ii = 1:n
x = rand(1,ii);
y = rand(1,ii);
X = x*ro+y*sqrt(1-ro^2);
if X > 1 % If X > 1 start iteration no. ii again until X is below 1
ii = ii - 1;
end
end
plot(x,X,'+')
Respuesta aceptada
Más respuestas (3)
Joseph Cheng
el 24 de Feb. de 2015
you'd want to use "continue" to skip the iteration.
for ind =1:5
if ind==3
continue
else
disp(ind)
end
1 comentario
Fredrik Slungård
el 25 de Feb. de 2015
Editada: Fredrik Slungård
el 25 de Feb. de 2015
Sean de Wolski
el 24 de Feb. de 2015
Why not just only generate random values that meet your criteria? Here's an example:
% Solve for x
syms x ro y
X = x*ro+y*sqrt(1-ro^2);
xx = solve(X,x)
% Plug in values
yval = -0.1;
roval = 0.3;
xmax = double(subs(xx,{y, ro},{yval,roval}));
% Generate only random numbers that meet criteria
xrand = rand(100,1)./xmax;
% Create X
Xfinal = xrand.*roval+yval*sqrt(1-roval^2);
% Check all X < 1
assert(all(Xfinal < 1))
1 comentario
Fredrik Slungård
el 25 de Feb. de 2015
Roger Stafford
el 25 de Feb. de 2015
Editada: Sean de Wolski
el 25 de Feb. de 2015
I am guessing that what you actually want is the following. It will give you 200 values in X which are all less than or equal to 1.
X = zeros(1,n);
x = zeros(1,n);
for ii = 1:n
b = true;
while b
t1 = rand;
t2 = t1*ro+rand*sqrt(1-ro^2);
b = t2 > 1;
end
X(ii) = t2;
x(ii) = t1;
end
plot(x,X,'+')
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!