Assume that you have two vectors named A and B of different lengths. Create a vector C that combines A and B in a manner similar to part a. However, if you run out of elements in one of the vectors, C also contains the elements remaining from the longer vector. For instance, if A has length m and B has length n where n>m, C = [A (1) B (1) A (2) B (2) ... A(m) B(m) B(m 1) B(m 2) … B(n)]
for two vectors of equal length I have:
a = 0:2:10
b = 1:2:11
c= [a;b]
c= c(:)'
Is there a simple way of doing this for unequal vector lengths? Solutions I found on Chegg are convoluted.
CodePudding user response:
Does this count as simple?
s = min(numel(a), numel(b)); % minimum of the two lengths
c = [reshape([a(1:s); b(1:s)], 1, []), a(s 1:end), b(s 1:end)];
It uses your approach for the minimum of the two lengths and then concatenates the remainder of the two vectors; but there will be at most only one non-empty remainder.
CodePudding user response:
I'm guessing this is homework, so I'll provide you with a simple step-by-step solution instead of a code:
- Pad
a
with as manyinf
's as you need to make it equal length asb
. (Indexing usingend 1
andnumel(b)
can be useful here) - Concatenate the two horizontal vectors below each other, and create a vertical vector using
(:)
. - Remove all
inf
-values from the result.
Note: Luis' solution is cleaner, but you might have a hard time explaining what is going on if you are asked questions.