How can I display a value of a vector for a specific value?
55 views (last 30 days)
Show older comments
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?
0 Comments
Answers (2)
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
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
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.
Bob Thompson
on 19 Feb 2019
Edited: Bob Thompson
on 19 Feb 2019
This can be done with logic indexing.
w2 = w(p==0);
0 Comments
See Also
Categories
Find more on Matrices and Arrays 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!