MATLAB Answers

Trying to modify a vector by removing alternate elements

4 views (last 30 days)
Hi ,
I am learning matlab and I came across a problem on cody:
I need to be able to remove even elements from a 1D vector:
if x= [ 1 8 5 9]
then y = [1 5]
I tried with somethin like this:
n=1;
y=x;
for i = 1:length(x)
if mod(n,2) == 0
y(n)=[];
end
n= n+1;
end
and I got this error:
Matrix index is out of range for deletion.
Error in for2 (line 5)
y(n)=[];

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 19 Jan 2020
Edited: Stephen Cobeldick on 19 Jan 2020
There is no point in defining n when it always has exactly the same value as the loop iteration variable i. Get rid of one of those variables.
Your code is buggy because you did not consider that when you remove elements from a vector it gets smaller, which is clear if you print the vector on each loop iteration. This is what your code does:
  1. iteration -> remove nothing [1 8 5 9]
  2. iteration -> remove 2nd value [1 5 9]
  3. iteration -> remove nothing [1 5 9]
  4. iteration -> remove 4th value [1 5 9] !!! EEROR: the vector does not have a 4th element !!!
What do you expect to happen when you try to remove the 4th element of a 3-element vector?
You can resolve this by looping over the vector in reverse:
for n = numel(y):-1:1 % reverse!
...
end
Or by getting rid of the loop and writing simpler, more efficient MATLAB code using basic indexing:
y(2:2:end) = []

  2 Comments

Hussain Bhavnagarwala
Hussain Bhavnagarwala on 19 Jan 2020
Thanks stephen,
the reversing solution worked for me!
I have a few questions:
1) is there a way to print the vector on every iteration in matlab
2) The second solution seems more simple, could you let me know where i can find more about it.

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Products


Release

R2019b

Translated by