extend an array with repeated values until another array values matches MATLAB

a=[2 3 4 7 9 12 15 18 22]
b=[2 7 15]

The result should be like this

c=[2 2 2  7 7 7 15 15 15];

The values should repeat until another matrix values matches. How can Matlab get me a solution for all problems related to this? Kindly help..

Answers


Assuming that a and b are sorted, you can try this

c = b(sum(bsxfun(@(x,y) x >= y, a, b(:))));

This results in

c =
     2     2     2     7     7     7    15    15    15

Please note that this works only if b(1) == a(1). If b(1) < a(1), b(1) will be repeated although it does not match a(1) and if b(1) > a(1) an error is thrown because a subscript index is smaller than 1.


Assuming that the first two numbers are always the same (otherwise what should the first number of the result be?):

prevj = b(1);
last = 1;
c = a;
for j = b(2:end)
    ind = find(c == j);
    c(last:ind-1) = prevj;
    last = ind;
    prevj = j;
end
c(last:end) = prevj;

Sorry about the messy code, but it seems to get the results you want (with a few assumptions).


Need Your Help

"Movie Format Not Supported" on iPhone with YouTube player in a WebView

iphone uiwebview youtube

I'm using a UIWebView on iPhone to play YouTube videos. This is working fine most of the time, but not all.

Is there any way to dump a sqlalchemy orm instance to json?

python json sqlalchemy

I wrote this function in python to dump an object to json. Is there any better and more tested way to do it using the library?