How to seperate an array into two?

1 visualización (últimos 30 días)
Jose Grimaldo
Jose Grimaldo el 2 de Abr. de 2020
Editada: dpb el 2 de Abr. de 2020
Im trying to seperate an array into two even variables using for loops. How can i do that?
I know that i can just do V1=V(1:2:end); V2=V(2:2:end); but I want to do it using for loops.
V=(8x1)
[r,c]=size(V)
V1=V(1);
V2=V(2)
for i=1:r-1
for j=1:(r/2)
V1(j)=V(i+2)
V2(j)=V(i+1)
end
  2 comentarios
dpb
dpb el 2 de Abr. de 2020
No loops needed...
V1=V(1:2:end);
V2=V(2:2:end);
I'd also strongly suspect there's really no reason to create two variables with sequential names; just reference the desired subset directly from the original.
Jose Grimaldo
Jose Grimaldo el 2 de Abr. de 2020
I know i can do that but I want to do it using for loops

Iniciar sesión para comentar.

Respuesta aceptada

dpb
dpb el 2 de Abr. de 2020
Editada: dpb el 2 de Abr. de 2020
Not a good idea still unless is homework...there are any number of ways to do so; about as simple as any would be
for i=2:2:numel(V)
j=i/2;
v1(j)=V(i-1);
v2(j)=V(i);
end
preallocate, of course.
As "exercise for Student", with minor alterations the above will work silently if the length of the input vector is odd as well. HINT: start w/
for i=1:2:numel(V)
j=???
...
instead and work form there...
Both, of course, presume the input vector is alternating odd-even rather than looking at what the values in the vector are and selecting by it.

Más respuestas (1)

Mohammad Sami
Mohammad Sami el 2 de Abr. de 2020
You can directly index into your 1-D vector.
V = rand(8,1);
n = length(V);
Vodd = V(1:2:n);
Veven = V(2:2:n);

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by