Adding 2 vectors in a specified position

1 view (last 30 days)
Hi, my question feel actually pretty easy but i am stuck.
Basically i want to obtain "z" with the even positions containing "y" and the odd position containing "x" (z=[1 12 2 13 3 14 ... 21 11])
How can i do this?
Thanks in advance
x=[ 1 2 3 4 5 6 7 8 9 10 11];
y=[12 13 14 15 16 17 18 19 20 21];
z=zeros(1,21);
for i=1:2:21
for j=1:length(x)
for k=1:length(y)
z(i)=x(j);
z(i+1)=y(k);
end
end
end

Accepted Answer

Image Analyst
Image Analyst on 18 Jul 2021
Try this:
% Obtain "z" with the even positions containing "y" and
% the odd position containing "x" (z=[1 12 2 13 3 14 ... 21 11])
x=[ 1 2 3 4 5 6 7 8 9 10 11];
y=[12 13 14 15 16 17 18 19 20 21];
z = zeros(1, length(x) + length(y));
% Counters for each independently allow for different lengths of x and y.
xCounter = 1;
yCounter = 1;
for k = 1 : length(z)
if mod(k, 2) == 1 && xCounter <= length(x)
z(k) = x(xCounter);
xCounter = xCounter + 1;
elseif yCounter <= length(y)
z(k) = y(yCounter);
yCounter = yCounter + 1;
end
end
z % Report to command window.
  2 Comments
Image Analyst
Image Analyst on 18 Jul 2021
Edited: Image Analyst on 18 Jul 2021
Note: if x and y are known to be the same length (which they are not in your example), it can be easier:
x=[ 1 2 3 4 5 6 7 8 9 10 11];
y=[12 13 14 15 16 17 18 19 20 21 22]; % Same length as x
z = reshape([x; y], 1, [])

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!