MATLAB Answers

Index of element to remove exceeds matrix dimensions.

15 views (last 30 days)
In my code x tends to change from 1 to 7. Here I took a sample value as 4. I want to delete the array element, if it has less than 0 or greater than 8 otherwise save the value in the array. xplus is an 1-D array. xplus maximum value will be 7 values. I tried this code it is getting error as
ERROR: Index of element to remove exceeds matrix dimensions.
Error in deletearraytest (line 5) xplus(x1)=[];
and workspace variable x=4 , x1=7, xplus=[5;6;7;8;0]
Here is my code x=4; xplus=zeros(7,1); for x1=1:7 if((x+x1<=0)||(x+x1>8)) xplus(x1)=[]; else xplus(x1)=x+x1; end end
I have check the solutions of many links but, I cant understand the mistake I did. Many people said that when we are going to delete the array element, it not going to be previous size. I need more explanation in that and solve my problem. I am amateur matlab user. Help needed. Thanks in advance.

  0 Comments

Sign in to comment.

Accepted Answer

Kevin Claytor
Kevin Claytor on 2 Mar 2016
Edited: Kevin Claytor on 2 Mar 2016
Because you're removing elements as you go, your array gets shorter, and your fixed index (1:7) can go out of bounds.
This is exactly what is happening when you have:
x1=7, xplus=[5;6;7;8;0]; xplus(x1)=[];
You're trying to remove the 7th element, when the array only has 5 elements in it.
A better way of accomplishing what you're doing is with logical indexing;
xplus(xplus < 0 | xplus > 8) = [];
which finds the elements of x < 0 or > 8 and removes them.

  1 Comment

Prasanna Venkatesh
Prasanna Venkatesh on 2 Mar 2016
Thank you so much,it worked. I was over this error for weeks and cant understand the concept also.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!