MATLAB: How to update size(Matrix,1) in for loop? I am receiving the “Index exceeds matrix dimensions” error.

for loopindexmatrixsize;

I am running into an issue as I am deleting rows in a matrix. As I delete rows, size(Matrix,1) changes, and I assume that is causing an error in the for statement. The error I receive is "Index exceeds matrix dimensions." Below is my first of two attempts at the code:
[~, ~, Matrix]=xlsread('TestEachSceneOnce.xls', 'Sheet1')
for m = 1:size(Matrix,1)
for n=1:size(Matrix,1)
if strcmp(Matrix(m,4),Matrix(n,4)) & Matrix{n,5}~='alreadydone' & m~=n % without m~=n, we would be checking if a cell is equal to itself

Matrix{n,5}='alreadydone'
Matrix(m,:)=[]
else
end
end
end
xlswrite('TestEachSceneOnce.xls', Matrix, 'Sheet2')
Therefore, I tried to update size(Matrix,1) each time a row is deleted in the code below. I still get the following error: "Index exceeds matrix dimensions."
[~, ~, Matrix]=xlsread('TestEachSceneOnce.xls', 'Sheet1')
UpdatedSizeOfMatrix=size(Matrix,1)
for m = 1:UpdatedSizeOfMatrix
for n=1:UpdatedSizeOfMatrix
if strcmp(Matrix(m,4),Matrix(n,4)) & Matrix{n,5}~='alreadydone' & m~=n % without m~=n, we would be checking if a cell is equal to itself
Matrix{n,5}='alreadydone'
Matrix(m,:)=[]
UpdatedSizeOfMatrix=size(Matrix,1)
else
end
UpdatedSizeOfMatrix=size(Matrix,1)
end
end
xlswrite('TestEachSceneOnce.xls', Matrix, 'Sheet2')
I would appreciate any help you can provide.

Best Answer

I think I answered my own question. First, I tried out looping backward (decrementing, or looping backward by -1) with a matrix:
%TheMatrix=[1;1;2;2;3;4;3;4]
TheMatrix=[6;1;1;6;4;3;7;7]
NewSize=size(TheMatrix,1)
%i is the number of rows in the array

for i=8:-1:1
for NewSize=NewSize:-1:1
if i~=NewSize & TheMatrix(i)==TheMatrix(NewSize)
OldSize=size(TheMatrix,1)
TheMatrix(i)=[]
TheMatrix
NewSize=size(TheMatrix,1)
if OldSize>size(TheMatrix,1)
break
end
else
NewSize=size(TheMatrix,1)
end
end
end
Then, I applied the appropriate code for a cell array:
[~, ~, Matrix]=xlsread('TestEachSceneOnce.xls', 'Sheet1')
NewSize=size(Matrix,1)
%i is the number of rows in the array
for i=9:-1:1
for NewSize=NewSize:-1:1
if i~=NewSize & strcmp(Matrix{i,4},Matrix{NewSize,4})
OldSize=size(Matrix,1)
Matrix(i,:)=[]
Matrix
NewSize=size(Matrix,1)
if OldSize>size(Matrix,1)
break
end
else
NewSize=size(Matrix,1)
end
end
end
xlswrite('TestEachSceneOnce.xls', Matrix, 'Sheet2')
This seems to be working. I am attaching the spreadsheet too. Thank you for your suggestion @WalterRoberson!