Trying to modify a vector by removing alternate elements

1 回表示 (過去 30 日間)
Hussain Bhavnagarwala
Hussain Bhavnagarwala 2020 年 1 月 19 日
コメント済み: Stephen23 2021 年 3 月 17 日
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)=[];

採用された回答

Stephen23
Stephen23 2020 年 1 月 19 日
編集済み: Stephen23 2020 年 1 月 19 日
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) = []
  4 件のコメント
Subham Kumar
Subham Kumar 2021 年 3 月 16 日
How do we use the second solution for a 2D array? I want to keep it a 2D array after removing the alternative elements.
Stephen23
Stephen23 2021 年 3 月 17 日
@Subham Kumar: do you mean like this?:
M = rand(4,3)
M = 4×3
0.2389 0.9783 0.6445 0.2981 0.6712 0.3533 0.8601 0.4258 0.1559 0.3875 0.8520 0.8540
M(2:2:end,:) = []
M = 2×3
0.2389 0.9783 0.6445 0.8601 0.4258 0.1559

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by