Adding 2 vectors in a specified position
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Dario Saracchi
el 18 de Jul. de 2021
Comentada: Dario Saracchi
el 19 de Jul. de 2021
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
0 comentarios
Respuesta aceptada
Image Analyst
el 18 de Jul. de 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 comentarios
Image Analyst
el 18 de Jul. de 2021
Editada: Image Analyst
el 18 de Jul. de 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, [])
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!