Reputation: 87
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..
Upvotes: 2
Views: 246
Reputation: 9317
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.
Upvotes: 2
Reputation: 3616
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).
Upvotes: 1