How to use a vector to index another vector?
22 views (last 30 days)
Show older comments
Hello, I am admittedly still fairly new to MATLAB, but I am working on something to expedite my research.
Essentially, I want to find the zero-crossing points of a signal. I'm currently using a filter (made by someone who actually knows what they're doing) to find all maxima and minima which are a certain value away from zero:
function out = PeakFinder(in,w)
out = in*0;
for i = w+1:length(in) - w
chunk = in(i-w:i+w);
[mx ind] = min(chunk);
if ind == (w+1);
out(i) = in(i);
end
end
This code gives me a nx1 column vector with either a zero (If the point is not a maximum) or the value of my input vector (If the point is a maximum) as a result. I'm then using find() to give me the row that point is located on in the vector. This gives me a ~15x1 vector
My issue is, I do not know how to use this 15x1 vector to find the values of the original nx1 vector. I tried using simple things like OriginalVector(NewVector) but that didnt work.
1 Comment
Sindar
on 24 Jan 2020
In what way did it not work? Error? Wrong values? There are more efficient ways, but your algorithm sounds like it should work
Answers (2)
Stephen23
on 24 Jan 2020
Edited: Stephen23
on 24 Jan 2020
That function output is rather fragile, as there is no way to distinguish zeros (data) from zeros (place holders). This could easily be rectified preallocating the output array with NaN or using a logical array instead, which would also simplify your task (as you could just use more efficient logical indexing). In any case, I don't see any reason why find should not work:
>> V = randi(9,13,1)
V =
6
7
3
8
3
9
1
3
8
5
2
9
1
>> W = PeakFinder(V,2)
W =
0
0
3
0
0
0
1
0
0
0
0
0
0
>> X = find(W);
>> V(X)
ans =
3
1
I do not see how this function helps you to "to find all maxima and minima which are a certain value away from zero".
Star Strider
on 24 Jan 2020
Testing the code (without the function definition or function call):
t = (0:0.1:15);
in = sin(t*2*pi);
w = 5;
out = in*0;
for i = w+1:length(in) - w
chunk = in(i-w:i+w);
[mx ind] = min(chunk);
if ind == (w+1);
out(i) = in(i);
end
end
figure
plot(t, in)
hold on
plot(t, out, 'p')
hold off
grid
reveals that when ‘out’ is not zero, it returns the troughs (negative peaks) of the ‘in’ vector.
To get the indices of the non-zero values in ‘out’:
indices = find(out);
and:
OriginalVector(indices);
should return the correct values.
0 Comments
See Also
Categories
Find more on Get Started with Signal Processing Toolbox 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!