loop/cycle for producing the following sequence of numbers A={1, 4, 5, 8, 9, ....} and/or B={2, 3, 6, 7, 10,....}

Hello guys, I have two vectors: X=[0 0 0 0 0] and Y =[-1 -1 -1 -1 -1] X=[x1 x2 x3 x4 x5] and Y=[y1 y2 y3 y4 y5] i want to create a third vector which will be a combination of the elements from both vectors in the following order: Z=[-1 0 0 -1 -1 0 0 -1 -1 0] Z=[y1 x1 x2 y2 y3 x3 x4 y4 y5 x5]
I want to use for cycle for moving the index i from the first element to the last element of the vector(s), however I'm don't know how I can manipulate the i in the body of the for cycle so I can access the appropriate element of the particular vector.
For example this for cycle is separating the indices to odd ones and even ones:for i=1:10 if (mod(i,2)==1) i %odd index end if (mod(i,2)==0) i %even index end end
I would need something similar to that. It doesn't has to be for cycle.
Thanks.

Réponses (1)

idx = repmat([1 1 0 0], 1, 3)
idx = idx(2:end-1);
X=[0 0 0 0 0], Y =[-1 -1 -1 -1 -1]
Z(idx == 0) = X;
Z(idx == 1) = Y;

2 commentaires

To work wathever the size of vectors X and Y (as long as they are the same length), start with:
assert(size(X) == size(Y) && isvector(x) && mod(numel(x), 2) == 1);
idx = repmat([1 1 0 0], 1, (numel(X) + 1) / 2);
if you're still wondering how to use a for loop to accomplish this then
think of the index locations of what would give you
for i =0:numel(Y)-1
if mod(i,2)==0
end

Cette question est clôturée.

Question posée :

le 1 Oct 2015

Clôturé :

le 20 Août 2021

Community Treasure Hunt

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

Start Hunting!

Translated by