Generate a vector with elements based on certain elements in another vector

50 visualizaciones (últimos 30 días)
Bob
Bob el 30 de Oct. de 2024 a las 8:26
Comentada: Bob el 30 de Oct. de 2024 a las 11:46
I have a simple question but do not know the code that will give me the answer. Can you help me with this? I would like to create a vector B with the same length as A. The elements in B should be zero, except for the first n elements after a certain value appears at the ih-th position in vector A.
For example, vector B should contain the value 1 for three following positions when the first 1 appears in A. This means that vector B = [0;0;0;0;0;1;1;1;0;0] if A = [0;0;0;0;0;1;1;1;1;1].

Respuestas (2)

Alan Stevens
Alan Stevens el 30 de Oct. de 2024 a las 9:08
Like this?
A = [0;0;0;0;0;1;1;1;1;1];
B =zeros(size(A));
ptr = find(A==1);
B(ptr(1):ptr(1)+2)=1
B = 10×1
0 0 0 0 0 1 1 1 0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  1 comentario
Bob
Bob el 30 de Oct. de 2024 a las 11:45
Yes, this is the solution. Thank you.
However, I would like to use a for loop with an if statement. Is this possible? Can you help me with this?

Iniciar sesión para comentar.


Shantanu Dixit
Shantanu Dixit el 30 de Oct. de 2024 a las 10:32
Editada: Shantanu Dixit el 30 de Oct. de 2024 a las 10:35
Hi Bob,
You can achieve the conditional vector by first creating a vector 'B' initialized to zeros and then assigning the value 1 to elements following the first occurrence of 1 in vector 'A'.
  • Use 'find' function to get the index ('ih') of the first occurrence of 1 in vector A.
  • Initialize 'B' as a zero vector of the same length as 'A'.
  • Set the next 'n' elements in 'B' to 1 starting from 'ih' by indexing (ensure indexing remains within array bounds)
I hope this helps!
You can refer to the MATLAB Onramp course to gain understanding on basic vector creation and indexing: https://matlabacademy.mathworks.com/details/matlab-onramp/gettingstarted
Also refer to the MathWorks documentation on following useful functions:

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by