inserting vectors into another new vector

조회 수: 50 (최근 30일)
Mohanned Al Gharawi
Mohanned Al Gharawi 2019년 12월 6일
답변: Mohanned Al Gharawi 2019년 12월 7일
Hello everybod,
Let’s say I have two vectors, A=[7 17 27] and B=[13 22], and later produce a new vector C as shown in the below process:
put the first number from A as the first number in C and put the first number form B as the second number in C and then put the second number from A as the third number in C then put the second number from B as the fourth number in C and keep going on the same process to the end.
That means, I should have the final result for C as [7 13 17 22 27].
Thank you
  댓글 수: 2
the cyclist
the cyclist 2019년 12월 6일
Will B always be exactly one element shorter than A? If not, can you please tell us more detail? For example, could A be the shorter one? Do we always use all elements from both vectors?
Mohanned Al Gharawi
Mohanned Al Gharawi 2019년 12월 6일
sometimes they are the same length or B shorter than one element from A.

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

채택된 답변

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019년 12월 6일
편집: JESUS DAVID ARIZA ROYETH 2019년 12월 6일
A=[7 17 27 35];
B=[13 22 30 15];
N = max(numel(A),numel(B));
C=[A nan(1,N-numel(A)); B nan(1,N-numel(B))];
C(isnan(C))=[]
C=C(:)'
  댓글 수: 2
Mohanned Al Gharawi
Mohanned Al Gharawi 2019년 12월 6일
@JESUS DAVID ARIZA ROYETH thank you so much for answering me, but I think there is a problem. I forgot telling you that sometimes both vectors have same length. Anyhow, when I add number to B and became like [13 22 30] it works ok, but when the two matrices became like A=[7 17 27 35] and B=[13 22 30]; the answer becomes:
C= 7 17 27 35 13 22 30
while it should become C=7 13 17 22 27 30 35
Thank you again for your help.
JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019년 12월 6일
I edited my answer, try again, did the test with several cases and it works fine

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

추가 답변 (3개)

the cyclist
the cyclist 2019년 12월 6일
Here is another way:
A = [7 17 27 35];
B = [13 22 30 31];
C = [A; [B nan(numel(A)-numel(B),1)]];
C = C(1:(numel(A)+numel(B)));

Mohanned Al Gharawi
Mohanned Al Gharawi 2019년 12월 6일
@JESUS DAVID ARIZA ROYETH thank you it works with several cases.

Mohanned Al Gharawi
Mohanned Al Gharawi 2019년 12월 7일
thank you it works also.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by