Removing entries of vector indexed by odd integer.

So, in a question we've been asked to define a vector "x" which begins at 1.5 and ends at -3.5 with 101 entries in between without the use of any loops. So, I used linspace(1.4, -3.5, 101) to do this. However the next part of the question requires you to create a matrix "y" which corresponds to "x" only with the entries indexed by an odd integer removed. How can you do this without using a loop? Is there a function for it? Thanks.

 채택된 답변

Leah
Leah 2013년 9월 25일

1 개 추천

You just have to reference every other element of the vector you created.
x=linspace(1.4, -3.5, 101) ;
y=x(1:2:end);

댓글 수: 1

David
David 2013년 9월 25일
Will that not include elements 1 and 101 though, and they're odd indexes? Why wouldn't it be y = x(2:2:100);?

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

추가 답변 (1개)

Matt J
Matt J 2013년 9월 25일
편집: Matt J 2013년 9월 25일

1 개 추천

x=linspace(1.4, -3.5, 101) ;
y=x;
y(1:2:end)=[];
or
y=x(2:2:end);

댓글 수: 9

David
David 2013년 9월 25일
y(1:2:end)=[]; or
y=x(2:2:end); seeing as these are two different lines of code, how is it that they work in the same way?
Matt J
Matt J 2013년 9월 25일
Because deleting odd x(i) is equivalent to keeping even x(i).
David
David 2013년 9월 25일
So, this y(1:2:end)=[] deletes the odd entries? Sorry for the basic questions. Literally only had our first lecture in this the other day.
Matt J
Matt J 2013년 9월 25일
Why don't you try and find out ;)
David
David 2013년 9월 25일
Hah. I would but I'm not in college and don't have MATLAB on my laptop. Would this y=x(2:2:end); not include the last element, which would be of index 103?
Leah
Leah 2013년 9월 25일
David there is a student version of MATLAB available for $99. I ended up using MATLAB for lots of other courses, not just numerical analysis where it was required.
It gets elements, 2,4,6,8,10,12,14,........98,100,102. It can't get 104 since there is no 104, and since it doesn't get odd numbers, it won't get 103 even though it is "end" because it is odd. Does that explain it better?
See also
>> 2:2:15
ans =
2 4 6 8 10 12 14
David
David 2013년 9월 25일
Brilliant! Thanks a million.

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

질문:

2013년 9월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by