0

For example, A = [19 20 21 22 23 24 25]; B = [2 0 3 0 0 0 2];

How can we get a new array, repeating each value from B accordingly X times?

For example, answer here is: [19 19 21 21 21 25 25].

Please note that I am only allowed to a for loop combined with a repmat call.

rayryeng
  • 102,964
  • 22
  • 184
  • 193
iAmWanteD
  • 303
  • 2
  • 9
  • We cannot use any other "complex" matlab functions.. (only 1 loop, and basic matlab functions..).. No idea what numel/bsxfun is.. this question is from an exam, we are tried to figure it out, but there are no solutions. – iAmWanteD Mar 15 '15 at 14:24
  • Your link is very complicated :( – iAmWanteD Mar 15 '15 at 14:24
  • 1
    How do you define "basic" MATLAB functions? The link also provides `cumsum` based approach which could be easier to follow. Also look [here](http://stackoverflow.com/q/1975772/3293881) for a simple implementation with `cumsum`! – Divakar Mar 15 '15 at 14:30
  • It is not possible by using only repmat or the for iteself? – iAmWanteD Mar 15 '15 at 14:52
  • Alright, so what did you try? Show your code. – Divakar Mar 15 '15 at 14:54
  • I'm not sure, but something like: A= [19 20 21 22 23 24 25]; B = [2 0 3 0 0 0 2]; for i=1:length(a) sorted(i) = repmat(b,1,shows(i)); end I know the syntax is incorrect, but maybe a repmat :S – iAmWanteD Mar 15 '15 at 15:31
  • @Osh24: I recommend to create a new question including all these additional informations. Here the variable names don't match your example, at least `shows` is undefined. – Daniel Mar 15 '15 at 16:22
  • @Osh24 Add those code details in the question and the edited question could be reopened then. You won't need post a new question. – Divakar Mar 15 '15 at 16:26

1 Answers1

0

If you are only allowed to use repmat and a for loop, you can do the following:

S = []; 
for idx = 1 : length(B) 
    S = [S repmat(A(idx), 1, B(idx))]; 
end

S is initially a blank array, then for as many values as there are in B (or A since they're both equal in length), simply concatenate S with each value in A that is repeated by the corresponding number in B. S will contain the output.

By running the above example, I get:

S =

    19    19    21    21    21    25    25

However, I highly recommend you use more vectorized approaches. I'll leave that to you as an exercise.

Good luck!

rayryeng
  • 102,964
  • 22
  • 184
  • 193