How to solve "Matrix index is out of range for deletion." error?
67 views (last 30 days)
Show older comments
Could anyone tell me how to solve this error? I attach the code as below. Thanks in advance
Error is .....
Matrix index is out of range for deletion.
Error in ModeShape (line 12)
K(:,[(6*(i-1))+1:(6*(i-1))+6])=[]
K=load('Job-1-1_STIF2.mtx') % The mtx. file has 3 columns with plenty of rows
for i=1:1:10
K([(6*(i-1))+1:(6*(i-1))+6],:)=[]
K(:,[(6*(i-1))+1:(6*(i-1))+6])=[]
end
1 Comment
Rik
on 17 Feb 2021
Are you sure you didn't make any mistake when writing the code that creates the indices? Did you try storing them in a separate variable to investigate the values?
Answers (2)
Rik
on 17 Feb 2021
Take a look at the indices on the second line:
i=1;
ind=(6*(i-1))+1:(6*(i-1))+6
Since you use them to index the columns (the second dimension) and you have only 3, this deletion will fail.
2 Comments
Rik
on 18 Feb 2021
Aha, so you don't actually have your actual matrix. How is Matlab supposed to know that your first column is the row index and the second column is the column index?
You can probably use accumarray to convert your data to the actual matrix, after which you can use the code you posted.
Steven Lord
on 18 Feb 2021
Suppose you were a pirate being forced to wash the plank that your pirate crew uses to force people to walk the plank. The plank is six paces long, so you clean then step forward. But what you don't realize is that the plank has rotted a bit, so as soon as you step onto it the last pace of the board falls off. So you wash, step forward, wash, step forward, and repeat this process. You wash the fifth pace of the plank and go to take a step forward ... but that sixth pace of plank is no longer there!
That's effectively what you're doing here. I've wrapped this example in try / catch so I can run both this example (which won't work) and the next (which will) in the same answer.
try
plank = 1:6;
for k = 1:length(plank)
fprintf("Washed element " + plank(k) + newline)
fprintf("Element " + (7-k) + " fell off!" + newline)
plank(7-k) = []
end
catch theError
disp("The operation threw the following error: " + newline + theError.message)
end
In this case the plank starts off with six elements, then five, then four, and finally when you try to wash element four the plank only has three elements.
You could resolve this by marking in a separate array which elements get deleted at each step and deleting them all at once after the loop is complete.
values = 2:10;
toDelete = false(size(values));
for ind = 1:numel(values)
if isprime(values(ind))
fprintf("Element %d (%d) is prime. Marking for deletion." + newline, ind, values(ind))
toDelete(ind) = true;
end
end
values(toDelete) = []
0 Comments
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!