How to insert multiple element after specific numbers in a vector?

9 visualizaciones (últimos 30 días)
Patrick Bourke
Patrick Bourke el 14 de Feb. de 2021
Comentada: the cyclist el 15 de Feb. de 2021
I have a logical vector, and i want to add elements after the 0's and after the 1's, but a different element after the 0's than the 1's. How do I do this.

Respuestas (1)

the cyclist
the cyclist el 14 de Feb. de 2021
Here is one way
% Original logical vector input
L = logical([1 0 1 1 0]);
% The numbers to be inserted
oneNum = 6;
zeroNum = 3;
output = [L; zeroNum*ones(1,length(L))];
output(2,L==1) = oneNum;
output = output(:)'
output = 1×10
1 6 0 3 1 6 1 6 0 3
  2 comentarios
Patrick Bourke
Patrick Bourke el 14 de Feb. de 2021
What if I want to add instead of 6, 666666, so like multiple in the place.
the cyclist
the cyclist el 15 de Feb. de 2021
If it is always the same number of repeats, then it is a straightforward extension of the above:
% Original logical vector input
L = logical([1 0 1 1 0]);
% The numbers to be inserted
oneNum = 6;
zeroNum = 3;
% Number of repetitions
repeats = 4;
output = [L; zeroNum*ones(repeats,length(L))];
output(2:end,L==1) = oneNum;
output = output(:)'
output = 1×25
1 6 6 6 6 0 3 3 3 3 1 6 6 6 6 1 6 6 6 6 0 3 3 3 3

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices 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