Adding 2 vectors in a specified position

2 ビュー (過去 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 Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by