How can I display a value of a vector for a specific value?

60 views (last 30 days)
I have two vectors:
p = [5 0 6 7 0];
w = [6 2 5 6 7];
How can I display in matlab that for every 0 in vector p, the program shows me the two elements in w, namely w1 = 2 and w2 = 7?

Answers (2)

Adam Danz
Adam Danz on 19 Feb 2019
Edited: Adam Danz on 25 Feb 2019
p = [5 0 6 7 0];
w = [6 2 5 6 7];
% Show the values in w that correspond to p==0
w(p==0)
ans =
2 7
  6 Comments
ntclrz
ntclrz on 20 Feb 2019
Thank you for the answer!
I'm realizing now the problem:
If I plot w (x-axis) and p (y-axis) I get this graph:
w_p.jpg
I know there are three values where p is approximately equal to zero (roots of the function). How can I determinate this roots when no p-value is equal to zero?
Adam Danz
Adam Danz on 20 Feb 2019
Edited: Adam Danz on 20 Feb 2019
That gets a little tricky. One way is to define a threshold such that any value that is within the 'threshold' distance from 0 is considered to be 0. Here's an example.
p = [5 0.01 6 7 -0.03];
w = [6 2 5 6 7];
thresh = 0.1;
%index of all values that are within 'thresh' distance to 0
isNearZero = abs(p) <= thresh;
w(isNearZero)
ans =
2 7
Another method is to use ismembertol(); play around with the 3rd input to suit your needs.
p = [5 0.001 6 7 -0.03];
w = [6 2 5 6 7];
% index of all values near 0
isNearZero = ismembertol(p, 0, .1);
w(isNearZero)
ans =
2 7
In either of these methods, if your data are finely sampled (which appears to be the case) expect that many values near 0 will be considered to be zero - not just the ones prior to crossing zero. There are more complicated ways around that if that turns out to be a problem.

Sign in to comment.


Bob Thompson
Bob Thompson on 19 Feb 2019
Edited: Bob Thompson on 19 Feb 2019
This can be done with logic indexing.
w2 = w(p==0);

Categories

Find more on Resizing and Reshaping Matrices 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!