How to subtract previous array element from the current one ?

17 views (last 30 days)
I have datastream as lines from the comport. All values are being parsed and I can choose the interested data. In this case, I want to subtract previous Easting value from the current one and calculate the distance between these two values each second when new string received. Could not create a 'for' loop for this operation;
s=serialport('COM14',115200);
configureTerminator(s,"CR/LF");
t = 0;
a = 0;
while true
t = t + 1;
line=readline(s);
ld=split(line,',');
Date=(ld{1});
UTC=(ld{2});
LAT=(str2double(ld{3}));
LONG=(str2double(ld{4}));
ALT=(str2double(ld{5}));
[Easting,Northing,UTMZone]=deg2utm(LAT,LONG);
HPOS=[Easting Northing];
SoG=(ld{6});
Depth=(ld{7});
CL=(ld{8});
AX=(str2double(ld{9}));
AY=(str2double(ld{10}));
AZ=(str2double(ld{11}));
GX=(str2double(ld{12}));
GY=(str2double(ld{13}));
GZ=(str2double(ld{14}));
MX=(str2double(ld{15}));
MY=(str2double(ld{16}));
MZ=(str2double(ld{17}));
Temp=(ld{18});
Bat=(ld{19});
ii=1:length(Date);
jj=2:length(Date);
test=zeros(length(HPOS),1);
for ix=1:length(Date)
test(ix)=HPOS(jj)-HPOS(ii);
end
end
when I run this code, I get the error message saying;
Index exceeds the number of array elements (2).
Error in Untitled5 (line 46)
test(ix)=HPOS(jj)-HPOS(ii);
Kind Regards,
Alper

Accepted Answer

Scott MacKenzie
Scott MacKenzie on 25 Jun 2021
Edited: Scott MacKenzie on 25 Jun 2021
If you want to
subtract previous Easting value from the current one
see below. The value you want is EastingDiff.
EastingSave = 0;
while true
...
[Easting,Northing,UTMZone]=deg2utm(LAT,LONG);
EastingDiff = Easting - EastingSave;
EastingSave = Easting;
...
end
To avoid the error, get rid of the six lines beginning with ii = . You don't need them.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!