# Math Help - Index exceeds matrix dimensions.

1. ## Index exceeds matrix dimensions.

I'm deleting a row from a matrix then writing it to a text file and am getting an error
------
??? Index exceeds matrix dimensions.

Error in ==> final_program at 125
fprintf(fid,'%s %s %s %s',guests{i, 1},guests{i, 2},guests{i, 3},guests{i, 4});
------
The matrix is good and I have checked it in MATLAB and it displays exactly how it should. I have this snippet of code working correctly in another switch statement when it needs to replace a cell array and then print to text file but once I try to use it to remove the cell row and print I get this annoying error. Thanks!

Here's the snippet of code in which it occurs.
Code:

% delete row from text file
[guests, lines] = show_guests('hotel.txt');
choices = guests;
choices(:,2:4) = [];
choices = choices';
[reservations, hh] = listdlg('ListString',choices, 'SelectionMode','single');
if hh == 1
% create the new data file
guests(reservations, :) = [];

% write the changes to text file
fid = fopen('hotel.txt', 'w+');
i=1;
for j=i:lines
if i ~= lines
fprintf(fid,'%s %s %s %s\n',guests{i, 1},guests{i, 2},guests{i, 3},guests{i, 4});
else
fprintf(fid,'%s %s %s %s',guests{i, 1},guests{i, 2},guests{i, 3},guests{i, 4});
end
i = i+1;
end
fclose(fid);
end

2. Originally Posted by thisisalex90
I'm deleting a row from a matrix then writing it to a text file and am getting an error
------
??? Index exceeds matrix dimensions.

Error in ==> final_program at 125
fprintf(fid,'%s %s %s %s',guests{i, 1},guests{i, 2},guests{i, 3},guests{i, 4});
------
The matrix is good and I have checked it in MATLAB and it displays exactly how it should. I have this snippet of code working correctly in another switch statement when it needs to replace a cell array and then print to text file but once I try to use it to remove the cell row and print I get this annoying error. Thanks!

Here's the snippet of code in which it occurs.
Code:

% delete row from text file
[guests, lines] = show_guests('hotel.txt');
choices = guests;
choices(:,2:4) = [];
choices = choices';
[reservations, hh] = listdlg('ListString',choices, 'SelectionMode','single');
if hh == 1
% create the new data file
guests(reservations, :) = [];

% write the changes to text file
fid = fopen('hotel.txt', 'w+');
i=1;
for j=i:lines
if i ~= lines
fprintf(fid,'%s %s %s %s\n',guests{i, 1},guests{i, 2},guests{i, 3},guests{i, 4});
else
fprintf(fid,'%s %s %s %s',guests{i, 1},guests{i, 2},guests{i, 3},guests{i, 4});
end
i = i+1;
end
fclose(fid);
end
It may not be your problem but you should not be modifying the lower limit of a for loop inside the loop.

CB