Relating values in one array indexed to another

1 view (last 30 days)
I was given some arrays that have been indexed in a funny way. I think the idea was to save space because these are multi-million-point arrays.
Here's the compression and indexing method: I have a compressed array of values a_val and corresponding index record numbers a_ind. I also have a much longer array of indices b_ind. For every record index in b_ind there is a matching a_ind. I want to find the values b_val which will correspond to the values in a_val, but will be the same length as b_ind. Here's what I have:
a_ind = [ 2 3 5 6 7 9 11 12 13 15];
a_val = [10 10 20 30 40 40 40 50 60 60];
b_ind = [2 2 2 3 5 5 6 6 7 9 9 9 11 12 12 13 13 15];
I want:
b_val = [10 10 10 10 20 20 30 30 40 40 40 40 40 50 50 60 60 60];
I can do this with a loop:
b_val = NaN(size(b_ind));
for k = 1:length(b_val)
b_val(k) = a_val(a_ind==b_ind(k));
end
but my arrays contain millions of elements and the loop takes several minutes to complete. I'm sure there is some clever way to use ismember, but I can't think of how. Any ideas?
  1 Comment
Chad Greene
Chad Greene on 3 Jul 2015
This works:
[~,lib] = ismember(b_ind,a_ind)
b_val = a_val(lib);
However, my b_ind dataset has a few indices not found in a_ind. If
b_ind = [2 2 2 3 5 5 6 6 7 9 9 9 11 12 12 13 13 15];
the ismember method throws a subscript index error because some lib values are zero.

Sign in to comment.

Accepted Answer

Chad Greene
Chad Greene on 3 Jul 2015
I figured it out.
[~,lib] = ismember(b_ind,a_ind)
b_val = NaN(size(b_ind));
b_val(lib>0) = a_val(lib(lib>0));

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!