2
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..

1
  • Can we assume that a and b are sorted to begin with? Commented Jul 17, 2012 at 19:29

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your reply....the previous post is enough for my work and it will be more useful for me...the condition b(1)==a(1) always satisfies..no problem.thank you very much
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.