Interleaving Vectors in MATLAB

조회 수: 63 (최근 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
Abiy Tsegaye Demissie 2019년 8월 15일
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