-1

I am trying to adapt a script that I wrote in MATLAB to be able to run in Octave, the error occurs at the first iteration of this for loop:

for b = (tp/ts):(td/ts)
Vc(b) = Vc(a) + (Vs-Vc(a)).*M(b-(tp/ts-1)); 
I(b) = (Vs-Vc(b))./R;                       
end
>> tp/ts
ans = 1.0000e+04
>> Vc(tp/ts) = 5;
error: Vc(10000-1.81899e-12): subscripts must be either integers 1 to (2^63)-1 or logicals
>> Vc(1e4) = 5;
>>

As you can see from the console, when I try to index Vc using tp/ts it throws the error, but when I use the value of tp/ts as the index it works fine. Can anybody explain where the extra "-1.81899e-12" is coming from in the index? And is there a workaround for this issue?

Thanks.

Edit: Changed screenshot images to text. This is my first question on here so thanks for your patience.

  • 2
    Floating point error? Please do not post code or error messages as images. If you'd like someone to be able to reproduce your problem and help you, please post a [mre] including definitions for all of the variables used. – beaker Aug 08 '23 at 14:48
  • `tp/ts` is not exactly 10,000, due to floating-point rounding errors (see linked Q&A). Use `round` to remove the fractional part. – Cris Luengo Aug 08 '23 at 16:15
  • Also: MATLAB and Octave round values to 5 or 6 digits for display. type `format long` to see the full number. – Cris Luengo Aug 08 '23 at 16:16
  • The duplicate isn't really a duplicate, but in any case, just to elaborate on what Cris was saying: what octave is trying to tell you is that, when performing indexing operations, your indices need to be integers. If not, octave warns you that you tried to index a matrix using a non-integer number. This makes sense: which element would you want if you tried to index with 2.5 for instance, the 2nd or the 3rd? Matlab is a bit more lenient here, and simply truncates the number to the nearest integer (or possibly floor?). Octave however treats this as a bug to protect against unintended behaviour. – Tasos Papastylianou Aug 09 '23 at 23:43
  • for loop only needs a 1D vector, whatever in it, to go from 1st element to the last one and use each value within each lap. However to index vector elements one mist use integers or logicals: The types for indexing is restricted as to point at things integers work, but floats !? – John BG Aug 11 '23 at 17:29
  • tp/ts may be exactly same value, but because of not an integer MATLAB, and for the case many other languages, no indexing takes place – John BG Aug 11 '23 at 17:31

0 Answers0