Borrar filtros
Borrar filtros

merging vectors together with alternating values

94 visualizaciones (últimos 30 días)
Andrew Luce
Andrew Luce el 28 de Mayo de 2019
Editada: Nils Odenwald el 2 de Sept. de 2021
Hello,
I want to merge two vectors like this:
A=[ 1; 2; 3; 4;] B=[5; 6; 7; 8;]
resulting vector
C=[1; 5; 2; 6; 3; 7; 4; 8;]
Thank you

Respuestas (4)

KALYAN ACHARJYA
KALYAN ACHARJYA el 28 de Mayo de 2019
Editada: KALYAN ACHARJYA el 28 de Mayo de 2019
vec=[A B]';
C=vec(:)
>> A=[ 1; 2; 3; 4]
Example:
>> A=[ 1; 2; 3; 4]
A =
1
2
3
4
>> B=[5; 6; 7; 8]
B =
5
6
7
8
>> vec=[A B]'
vec =
1 2 3 4
5 6 7 8
>> C=vec(:)
C =
1
5
2
6
3
7
4
8
>>

Star Strider
Star Strider el 28 de Mayo de 2019
Try this:
A=[1; 2; 3; 4];
B=[5; 6; 7; 8];
C = [A(:) B(:)]';
C = C(:)
producing:
C =
1
5
2
6
3
7
4
8
  2 comentarios
Stephen23
Stephen23 el 28 de Mayo de 2019
Editada: Stephen23 el 28 de Mayo de 2019
+1 nice use of colon to ensure the orientation.
Star Strider
Star Strider el 28 de Mayo de 2019
@Stephen — Thank you! I want it to be as robust as possible.

Iniciar sesión para comentar.


Indrasish Chakraborty
Indrasish Chakraborty el 19 de Ag. de 2021
What if the two vectors are of unequal length ?
For example -
A=[2 4 5 7 8]
B=[3 8 0 1]
Then how to get C=[2 3 4 8 5 0 7 1 8] ?
  2 comentarios
shikhar tyagi
shikhar tyagi el 19 de Ag. de 2021
A=[1; 0; 3; 4 ;6 ;0];
B=[5; 6; 7 ;0 ;4];
C=cat(1,A,B);
C([1:2:end,2:2:end])=C
I hope this helps

Iniciar sesión para comentar.


Nils Odenwald
Nils Odenwald el 2 de Sept. de 2021
Editada: Nils Odenwald el 2 de Sept. de 2021
I recommend the MATLAB function "reshape", which allows you to change the order of arrays. You can also manipulate different data types such as strings.
Example:
A = [1; 2; 3; 4; 5];
B = [0; 0; 0; 0; 0];
result = reshape([A B]',[],1)
result = 10×1
1 0 2 0 3 0 4 0 5 0

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by