How to make a vector linearly spaced?

9 views (last 30 days)
Hamb BB
Hamb BB on 5 Jul 2016
Edited: Hamb BB on 15 Jul 2016
Hello everyone,
I have generated the timestamps for the charging power of a battery in the form of:
t=[7.2285 8.2285 16.4685 ...]
I have been trying to make this data linearly spaced, as in:
t2=[0.0000 0.0001 ... 7.2285 ... 8.2285 ... 16.4685]
I've tried the index method to find the index of the matching values as follows:
t3=0:0.0001:24;
for m=1:length(t3)
ind=find(t(:,1)==t3(m,1),1);
end
It always returns a zero matrix.
I can then use the index of the matching values to find the corresponding values in another vector. I've been at it for the last three hours, but I can't seem to find a matching value between the two vectors.
Is there a way to simply add linearly increasing values in the vector?

Accepted Answer

Stephen23
Stephen23 on 5 Jul 2016
Edited: Stephen23 on 5 Jul 2016
It is quite likely that your two vectors do not actually have exactly the same values, due to floating point number precision. This has been explained in many forums and threads:
The solution is to compare the difference between the values against a tolerance value:
>> t = [7.2285 8.2285 16.4685];
>> vec = 0:0.0001:24;
>> tol = 0.00005;
>> idx = any(abs(bsxfun(@minus,vec,t(:)))<tol,1);
>> find(idx)
ans =
72286 82286 164686
>> vec(idx)
ans =
7.2285 8.2285 16.4685
  2 Comments
Guillaume
Guillaume on 5 Jul 2016
I would use ismembertol instead of a bsxfun expression in this case.
As a bonus, by default, the tolerance of ismembertol is relative to the magnitude of the numbers.
Hamb BB
Hamb BB on 15 Jul 2016
Edited: Hamb BB on 15 Jul 2016
Unfortunately I have the 2013 version that doesn't have ismembertol.
I ended up using Stephen's method. I stored the find(idx) and then used the vector to simply pick the values from a corresponding vector of power values.

Sign in to comment.

More Answers (2)

Guillaume
Guillaume on 5 Jul 2016
As Stephen's says, your t3 and t don't match because of floating point errors. You need to use a tolerance to perform the comparison instead of pure equality. I.e. instead of
a == b
use
abs(a-b) <= some_tolerance
However, since you want to find the location of elements of a vector within another vector, allowing some tolerance for equality, there is now (since 2015a) ismembertol. This will return all your indices in one go, no need for a loop:
t3 = 0:0.0001:24
[found, indices] = ismembertol(t, t3) %use default relative tolerance of 1e-12
assert(all(found), 'some elements of t were not found in t3 within the given tolerance')

Thorsten
Thorsten on 5 Jul 2016
I cannot reproduce the error. This works fine for me:
t=[7.2285 8.2285 16.4685];
t2 = 0:0.0001:t(end);
[f idx] = ismember(t, t2)

Categories

Find more on Electrical Block Libraries in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!