Help with looping problem
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Here I am defining x and y coordinates of rays vertically approaching a boundary (currently sin(x))
x = 0:0.1:pi
rx1 = [x(1) x(1)] % x-coordinates, incoming ray 1
ry1 = [y0 sin(x(1))] % y-coordinates, incoming ray 1
rx2 = [x(2) x(2)] % x-coordinates, incoming ray 2
ry2 = [y0 sin(x(2))] % y-coordinates, incoming ray 2
rx3 = [x(3) x(3)] % x-coordinates, incoming ray 3
ry3 = [y0 sin(x(3))] % y-coordinates, incoming ray 3
and so on for the length of vector (x) = 32
Clearly this isn't a good way to write the program. The alternative approach I have tried to use is the following:
i = 1
for i = 1:length(x)
rx(i) = [x(i) x(i)]
ry(i) = [y0 sin(x(i))]
end
Which returns the error:
In an assignment A(I) = B, the number of elements in B and I must be the same.
So clearly this isn't the way to achieve what I was trying to do. I would greatly appreciate if someone could help me resolve this, as I have been stuck on it for some time.
0 comentarios
Respuesta aceptada
Matt Fig
el 23 de Oct. de 2012
Why would you want to create 64 variables like that? What a mess it would be to deal with in further steps. Perhaps two cell arrays could get the job done:
for ii = 1:length(x)
rx{ii} = [x(ii) x(ii)]; % rx is a cell array.
ry{ii} = [y0 sin(x(ii))];
end
Now the really important question is why do you need to do this at all? What is your next step that requires you to have these arrays as individuals, rather than just using x and sin(x)?
Más respuestas (3)
Matt Kindig
el 23 de Oct. de 2012
Editada: Matt Kindig
el 23 de Oct. de 2012
I'm not entirely clear what you want, but I think this will do the trick:
x = (0:0.1:pi)';
rx = [x, x];
ry = [ repmat(y0, size(x)), sin(x)];
This implements the vector as specified in the for loop you have shown, which is the preferred way to specify matrix data in Matlab (not creating variables for each line, as your rx1, rx2, etc. example shows).
1 comentario
Azzi Abdelmalek
el 23 de Oct. de 2012
y0=1
x = 0:0.1:pi
n=length(x);
eval(sprintf('rx%d=[x(%d) x(%d)],',repmat((1:n),3,1)))
eval(sprintf('ry%d=[y0 sin(x(%d))],',repmat((1:n),2,1)))
0 comentarios
Ver también
Categorías
Más información sobre Discrete Data Plots en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!