Comparing Vector Elements (of 2 vectors)

2 ビュー (過去 30 日間)
Michael
Michael 2013 年 4 月 3 日
Hello,
I have two vectors (one with random numbers 0-1, and the other which is essentially a set of strictly increasing numbers--up to just above 1)... (Maybe this isn't the best way to explain my problem but what I"ve said is true)
It'll be easier to give an example (for me) than to try to form my question more rigorously, so excuse my rough edges for a sec here..
Imagine two vectors which we'd like to compare the elements of:
P = [1 1.5 3 4 5.5 6 7 8 9 10 ];
R = [0.1014 1.6421 9.0088 5.7822 5.2368 0.3141 8.8437 3.1157 1.8910 2.9378];
I would like a new matrix which gives the index value for each time something like: P(i) <R(Any element)<P(i+1)...
The result for above would be:
comp = [ 1 2 9 5 5 1 8 3 2 2] I picked the index of P where R was ~(just above) P...
If this is unclear (which it totally is, I'm sorry) please ask me to clarify.
Many thanks, Michael
  3 件のコメント
Michael
Michael 2013 年 6 月 10 日
You're correct! I was typing fast and came up with a bad example that I didn't think through properly!
I decided to use loops over each element in the one vector, and loop over the other vector as well! Is there something easier or quicker than this??
Thanks in advance!
Matt Kindig
Matt Kindig 2013 年 6 月 10 日
Did you see my answer below?

サインインしてコメントする。

採用された回答

Matt Kindig
Matt Kindig 2013 年 4 月 3 日
編集済み: Matt Kindig 2013 年 6 月 10 日
I think this should do what you want:
Rc = mat2cell(R, 1, ones(size(R)));
comp = cellfun(@(x) find(P<x,1,'last'), Rc, 'UniformOutput', false);
tf = cellfun(@isempty, comp, 'UniformOutput', true); %get empties
comp(tf) = {0}; %default value if none found
comp = cell2mat(comp);
Or an even more direct way:
Rc = mat2cell(R, 1, ones(size(R)));
comp = cell2mat(cellfun(@(x) sum(P<x), Rc, 'UniformOutput', false));
Note that both of these assume P is sorted (which is, of course, the only way your question makes sense.).
  2 件のコメント
Matt Kindig
Matt Kindig 2013 年 6 月 10 日
I can't believe I overlooked the most obvious way!
One liner:
[~, comp]= histc(R, P);
Michael
Michael 2013 年 6 月 13 日
jenyus!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by