How to insert an element after each number in a vector?
15 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
laith Farhan
el 5 de Mayo de 2019
Comentada: Star Strider
el 5 de Mayo de 2019
Dear all,
I would like to add an element after each value in a vector, for example:
a=[10,2,40,58,100,90,40,30,4];
I would like to add 1 to vector values:
result = [1,10,1,2,1,40,1,58,1,100,1,90,1,40,1,30,1,4,1];
Help me please.....
1 comentario
Image Analyst
el 5 de Mayo de 2019
Instead of "after each number" don't you mean "after each number, EXCEPT the first number, where the number is also before the first number?" That's what Star and Adams solutions do. Or do you really mean what you said, instead of the "result" you gave, and so there would be no 1 at the beginning?
Respuesta aceptada
Star Strider
el 5 de Mayo de 2019
One approach:
a=[10,2,40,58,100,90,40,30,4];
result = [ones(size(a)); a];
result = [result(:); 1]'
producing:
result =
1 10 1 2 1 40 1 58 1 100 1 90 1 40 1 30 1 4 1
4 comentarios
Más respuestas (2)
Adam Danz
el 5 de Mayo de 2019
result = [reshape([ones(size(a));a],length(a)*2,1);1]';
3 comentarios
KALYAN ACHARJYA
el 5 de Mayo de 2019
Editada: KALYAN ACHARJYA
el 5 de Mayo de 2019
Nice one, +1, I tried, but can't
Image Analyst
el 5 de Mayo de 2019
Instead of "after each number" did you mean "after each number, EXCEPT the first number, where the number is also before the first number?" That's what Star and Adam's solutions do. Or do you really mean what you said, instead of the "result" you gave, and so there would be no 1 at the beginning?
Just to be complete and cover all ambiguities, I'll give the other solution. If you really want what you said in words, rather than the numerical result you gave, then use this code:
result = [a; ones(size(a))]
result = result(:)'
The result is:
result =
10 1 2 1 40 1 58 1 100 1 90 1 40 1 30 1 4 1
Note: 1's are only after the numbers and not before the first one.
Ver también
Categorías
Más información sobre 2-D and 3-D 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!