'Matlab resample array based on second array
Let's say I have two datasets, both consisting of an x and y array, e.g.:
x_1 = [1 2 3 4 5 6 7 8 9 10];
y_1 = [8 12 20 3 4 9 10 55 3 2];
x_2 = [2 5 6 8 9];
y_2 = [4 18 3 12 1];
Now, I'd like to calculate a new metric z = y_1 ./ y_2 but I want to compare elements of y_1 by elements of y_2 with the same x, value:
z = [12 4 9 55 3 2] ./ [4 18 3 12 1]
How can I then find this second array containing only the values of y_2 with a corresponding x_2 value that occurs in x_1 in an efficient way?
So far, I came up with this solution but I doubt it's the most efficient possibility:
for i = 1:numel(x_2)
z(i) = y_2(i) / y_1(y_1 == x_2(i));
end
Since looping over elements can generally be avoided in Matlab, I assume there's better ways to do this.
So basically, I want to resample the second dataset to make its x_2 array equal to x_1
Solution 1:[1]
You can vectorize this using ismember:
[Lia,Locb] = ismember(x_1, x_2);
z = y_1(Lia) ./ y_2(nonzeros(Locb).');
Whether you should or not is another question. Avoiding loops in MATLAB is largely an obsolete strategy since MATLAB started introducing the JIT compilation engine. I have my doubts that vectorized version will be any faster than the for-loop, except maybe for the largest datasets, and I don't believe it is any more readable. YMMV
Solution 2:[2]
Similar to previous answer, but shorter:
y_1(ismember(x_1,x_2))./y_2
Note: I've checked this on Octave, as don't have Matlab license.
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 | beaker |
| Solution 2 | Dmitry Messerman |
