Interleaving Vectors in MATLAB

262 次查看(过去 30 天)
David Kellie
David Kellie 2019-8-13
评论: Safwan 2024-3-13
We have a question to interleave two vectors using a for loop:
For this problem you have to modify the code in your file so that, using a for-loop, you interleave the elements of A and B creating a new vector called C. You can assume that A and B are the same length.
Testing
For this question you should, in a text file called, q2c.txt write a table containing three new test cases. As a reference example, two possible test cases for this are:
A B C
[1 2 4] [5 6 7] [1 5 2 6 4 7]
[-1 0 2] [7 3 1] [-1 7 0 3 2 1]
Coding
Now code your solution to the problem above in your q2c.m file. Make sure you include some code at the end to display the vector C after the loop has finished running.
  1 个评论
Steven Lord
Steven Lord 2019-8-14
Since this sounds like a homework assignment, please show us what you've done so far to try to solve the problem and ask a specific question about where you're having difficulty and we may be able to provide some guidance.

请先登录,再进行评论。

回答(2 个)

Andrei Bobrov
Andrei Bobrov 2019-8-14
编辑:Andrei Bobrov 2019-8-15
Without loop:
A = [1 2 4];B = [5 6 7];
C = [A;B];
C = C(:)';
with loop:
for ii = numel(A):-1:1
C(2*ii-[0 1]) = [B(ii),A(ii)];
end
  2 个评论
David Kellie
David Kellie 2019-8-14
Our question asks for a for loop. Can you provide an answer with a for loop?
Rik
Rik 2019-8-15
The loop version lacks pre-allocation (which is mostly dealt with by looping backward). However, this will still cause an issue if C already exists. The code below makes more sense to me.
C=zeros(1,2*numel(A));
for ii = 1:numel(A)
C(2*ii-[1 0]) = [A(ii),B(ii)];
end

请先登录,再进行评论。


Abiy Tsegaye Demissie
What a coincidence because I had the same question for my practical assignment.
So what I did was I used a for loop then used an if statement.
A=[1 3 5];
B=[2 4 6];
C=[ ];
for i = 1:length(A) %I am not sure about the length but it seems to work
if A(i)~=B(i)
C = [C A(i) B(i)];
end
if A(i)==B(i) %This is to ensure that it also works for vectors with the same numbers
C = [C A(i) B(i)];
end
end
disp(C)
Result 1 2 3 4 5 6
This is the best I can do. I do not know if there is a better way of doing this using a for loop. This seems to work well.
  2 个评论
Rik
Rik 2019-8-15
The length function should avoided. Either use numel, or use size(___,dim). Also, you don't need the comparison, you always need to do the same. If you did need the comparison, it would be clearer if you used an else instead of a new if with the inverted test.
Safwan
Safwan 2024-3-13
Thanks for the tips guys. I was struggling to do this for my prac.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by