Adding 2 vectors in a specified position

조회 수: 1 (최근 30일)
Dario Saracchi
Dario Saracchi 2021년 7월 18일
댓글: Dario Saracchi 2021년 7월 19일
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

채택된 답변

Image Analyst
Image Analyst 2021년 7월 18일
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
Image Analyst
Image Analyst 2021년 7월 18일
편집: Image Analyst 2021년 7월 18일
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 2021년 7월 19일
Thank you so much!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by