# How can I solve this problem?

2 views (last 30 days)
flashpode on 19 Feb 2022
Answered: Voss on 19 Feb 2022
I got a loop that reads the messages and gets the information of these messages, while looping it stops due to a common error. How can I solve it. My code is:
for i=1:1:P
seq1 = AIS2(i);
linia=convertStringsToChars(seq1);
if linia(13)=='A' && linia(15)=='1'
sequencia = ais_to_bit(linia(15:44));
s_longitud=sequencia(62:89);
longitud = bin2dec(num2str(s_longitud))/600000; lon1 = [lon1, longitud];
s_latitud=sequencia(90:116);
latitud = bin2dec(num2str(s_latitud))/600000; lat1 = [lat1, latitud];
pos_lat = 1:numel(lat1); value_lat = lat1(lat1>50); index1 = pos_lat(lat1>50);
lat1(index1) = [];lon1(index1) = [];
pos_lon = 1:numel(lon1); value_lon = lon1(lon1>3); index2 = pos_lon(lon1>3);
lat1(index2) = []; lon1(index2) = [];
end
end
and the error I get is:
Index exceeds the number of array elements. Index must not exceed 35.
Error in NewCode (line 37)
sequencia = ais_to_bit(linia(15:44));
I understand the problem as I have read about it in other posts, how could I program it as if it happens with a message ust delete this message and continue with the loop?

Voss on 19 Feb 2022
This will capture any errors that happen in that if block, display the error message to the command line, and continue with the loop.
for i=1:1:P
seq1 = AIS2(i);
linia=convertStringsToChars(seq1);
try
if linia(13)=='A' && linia(15)=='1'
sequencia = ais_to_bit(linia(15:44));
s_longitud=sequencia(62:89);
longitud = bin2dec(num2str(s_longitud))/600000; lon1 = [lon1, longitud];
s_latitud=sequencia(90:116);
latitud = bin2dec(num2str(s_latitud))/600000; lat1 = [lat1, latitud];
pos_lat = 1:numel(lat1); value_lat = lat1(lat1>50); index1 = pos_lat(lat1>50);
lat1(index1) = [];lon1(index1) = [];
pos_lon = 1:numel(lon1); value_lon = lon1(lon1>3); index2 = pos_lon(lon1>3);
lat1(index2) = []; lon1(index2) = [];
end
catch ME
disp(ME.message);
continue
end
% Note: 'continue' above is only necessary if you have more code down
% here that you want to skip when there is an error above.
end
Or you can just capture errors that happen on that one line that gives the error now (and display it and continue as above):
for i=1:1:P
seq1 = AIS2(i);
linia=convertStringsToChars(seq1);
if linia(13)=='A' && linia(15)=='1'
try
sequencia = ais_to_bit(linia(15:44));
catch ME
disp(ME.message);
continue
end
s_longitud=sequencia(62:89);
longitud = bin2dec(num2str(s_longitud))/600000; lon1 = [lon1, longitud];
s_latitud=sequencia(90:116);
latitud = bin2dec(num2str(s_latitud))/600000; lat1 = [lat1, latitud];
pos_lat = 1:numel(lat1); value_lat = lat1(lat1>50); index1 = pos_lat(lat1>50);
lat1(index1) = [];lon1(index1) = [];
pos_lon = 1:numel(lon1); value_lon = lon1(lon1>3); index2 = pos_lon(lon1>3);
lat1(index2) = []; lon1(index2) = [];
end
end