Help switching variables in a vector using a for loop

조회 수: 5 (최근 30일)
Nguyen
Nguyen 2015년 2월 16일
편집: James Tursa 2015년 2월 16일
These are the instructions that my professor gave me.
Out of place solution
a. Within the body of your function to reverse the input, create the output vector using the zeros function: myOuputVect = zeros(1, length(inputVect));
b. Create a counter variable to count backward. It should be set to the length of the input vector. The counter must be initialized before the loop starts.
c. The for-loop should count from 1 to the length of the input vector by an increment of one.
d. Within the body of the for-loop, use the loop counter and the backward counter to index your two vectors (input vector and output vector).
i. Use the loop counter for the input vector.
ii. Use the backward counter for the output vector.
iii. Copy the input vector value (only one value!) into the output vector.
iv. Decrement the backward index counter by one.
v. The loop will repeat until finished.
And this is what I have in my function file right now.
function [ myOutputVect ] = reverse_order( inputVect )
myOuputVect = zeros(1, length(inputVect));
bcount=length(inputVect);
for s_vec= [1:length(inputVect)]
end
end
When I got to part D of this problem I got pretty confused as to how I do this without using the swap operation.
  댓글 수: 1
Geoff Hayes
Geoff Hayes 2015년 2월 16일
Nguyen - you have two vectors, inputVector and myOutputVector, and two counters, s_vec for the input vector (i) and bcount for the output vector (ii). The question is asking you two swap the data from one vector to the other so that the output vector is the reverse of the input. So how might you implement iii?

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

답변 (1개)

James Tursa
James Tursa 2015년 2월 16일
편집: James Tursa 2015년 2월 16일
You made a good start, but need to fill out the insides of the for-loop.
Part d.iii is instructing you to have one line inside the for-loop that copies one element of the input vector to one element of the output vector. Part d.i tells you to use the loop counter s_vec as the index for the input vector element in this line. Part d.ii tells you to use the backward counter bcount as the index for the output vector element in this line. So, write one line inside your for-loop that does all of this (i.e., with an assignment statement).
Part d.iv is instructing you to have another separate line inside the for-loop that subtracts 1 from bcount.

카테고리

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