Adding 2 vectors in a specified position

14 Ansichten (letzte 30 Tage)
Dario Saracchi
Dario Saracchi am 18 Jul. 2021
Kommentiert: Dario Saracchi am 19 Jul. 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

Akzeptierte Antwort

Image Analyst
Image Analyst am 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 Kommentare
Image Analyst
Image Analyst am 18 Jul. 2021
Bearbeitet: Image Analyst am 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, [])
Dario Saracchi
Dario Saracchi am 19 Jul. 2021
Thank you so much!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by