'Typecast to an int in Octave/Matlab
I need to call the index of a matrix made using the linspace command, and based on some data taken from an oscilloscope. Because of this, the data inputed is a double. However, I can't really call:
Time[V0Found]
where V0Found is something like 5.2 however, taking index 5 is close enough, so I need to drop the decimal. I used this equation to drop the decimal:
V0FoundDec = V0Found - mod(V0Found,1)
Time[V0FoundDec]
However, even though that drops the decimal, octave still complains about it.
So, what can I do to typecast it to an int?
Solution 1:[1]
In MATLAB, it should be int8(x) or int16(x) or one of the other integer casts.
But I'm surprised you need to do that for an index. Try
myarray(floor(indexlist))
or
myarray(round(indexlist))
where myarray is your array and indexlist is your vector of noninteger indices.
example:
octave-3.2.3:8> v=rand(1,8)*10+1
v =
3.1769 1.4397 8.7504 1.7424 6.9413 3.1663 8.4085 9.0179
octave-3.2.3:9> a = (1:1:20).^2
a =
Columns 1 through 15:
1 4 9 16 25 36 49 64 81 100 121 144 169 196 225
Columns 16 through 20:
256 289 324 361 400
octave-3.2.3:10> a(floor(v))
ans =
9 1 64 1 36 9 64 81
Solution 2:[2]
You could use round, floor, ceil functions instead of your formula to do the rounding.
By the way, indexing is done using parenthesis instead of brackets so:
V0FoundDec = round(V0Found);
Time(V0FoundDec) % not Time[V0FoundDec]
In case that was your problem
Solution 3:[3]
In Matlab, the right way to do this is to use the interp1 function to interpolate. The format of this command is
yout = interp1 (xdata, ydata, xin, ...)
or
yout = interp1 (ydata, xin, ...)
where xdata is then assumed to be 1:length(ydata).
If you want to produce the result you would get from calling
V0FoundDec = Time(round(V0found))
you would say
V0FoundDec = interp1(Time, V0found, 'nearest')
but you can just as easily get linear interpolation (this is the default) with
V0FoundDec = interp1(Time, V0found)
or
V0FoundDec = interp1(Time,V0found,'linear')
and you can also extrapolate outside the limits (using 'extrap' or providing an extrap value), where
Time(round(V0found))
will crash if round(V0found) < 1 or > length(Time)
Solution 4:[4]
For those using Octave, the cast function does the job:
octave:1> cast(5.2,'int8')
ans = 5
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Azim J |
| Solution 3 | Cris Luengo |
| Solution 4 | alek |
