I just recently switched from MATLAB to Octave because my license ran out and I wanted to give it a shot before renewing, so I can't check the behavior in MATLAB right now. I am not sure if I am making a grave mistake here, but I am having some headache over a for-loop in Octave.
The loop was supposed to find the first "large" change ( 0.08
) in the values of one of the columns (column 5
in this case) of a csv-file I previously read with dlmread()
, and then return to me the index of the first change so I can discard all the data before this first big change occurs for my further computations.
While trying to solve this I remembered that one should avoid for-loops in MATLAB (and probably Octave as well), and I managed to get the result I want by just doing
idx = find(diff(gpsdata(:,5)) > 0.08, 1);
which is obviously much cleaner (and probably faster too?) and I will stick with it; however, I am still wondering why the for-loop is showing this weird behavior.
Is there a mistake in my code, or is that just a sign of why for-loops should be avoided in Octave/MATLAB? Are for-loops parallelized in Octave/MATLAB, is that why this is happening?
for (jj = 1:(size(gpsdata, 1) - 1))
if (gpsdata(jj, 5) + 0.08 < (gpsdata(jj+1, 5)))
idx = jj;
disp(["jj=" num2str(jj) ", idx=" num2str(idx)]);
printf("Found index %d, at %f s real time\n", num2str(idx), gpsdata(idx, 2));
break;
end
end
jj=380, idx=380
Found index 51, at 56.000000 s real time
Found index 48, at 19.770000 s real time
jj=380, idx=380
Found index 380, at 19.770000 s real time
The disp()
call produced the correct output, while the printf()
is somehow executed twice on top of returning wrong values, with only the fourth of the 4 arguments being correct (the 19.770000
is the expected output here); the other 3 values ( 51
, 56.000000
, and 48
) are wrong.
The data I am using for gpsdata
can be found here , and read in with data=load("~/gpsdata.mat");
followed by gpsdata=data.gpsdata;
.
As pointed out by @rahnema1, I was passing a string
instead of an int
by doing printf("%d", num2str(idx))
so Octave was printing the ascii codes for "380"
, which happen to be 51
, 56
, 48
.
Doing printf("%d", idx)
yields the expected behavior.
Thanks for catching that!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.