0

Here I got

A = [1, 2, 3]

B = [1, 0, 0, 1, 0, 1]

I want to create a matrix

C = [1, 0, 0, 2, 0, 3]

You can see B is like a mask, The number of ones in B is equal to the number of elements in A. What I want is arrange elements in A to the place where B is 1.

Any method without loop?

ederag
  • 2,409
  • 25
  • 49
Haoliang
  • 1,047
  • 3
  • 12
  • 14

1 Answers1

3

Untested, but should be close:

C = zeros(size(B));
C(logical(B)) = A;

This relies on logical indexing.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • Just wanted to post the same solution, using `C(find(B)) = A;` but this results in the same. – Nemesis Oct 18 '14 at 18:07
  • 1
    @Nemesis `logical` is probably faster than `find` – Luis Mendo Oct 18 '14 at 19:08
  • 1
    @LuisMendo Would be interesting to test out whether `==1` is faster than `logical()` though or maybe it's the other way around or maybe it's the same. – Divakar Oct 18 '14 at 19:48
  • @Divakar a quick test in Octave shows that `== 1` is slightly faster that `logical()`. However, they have different results. A fairer comparison would be against `!= 0` which is still a itsy bitsy quicker. – carandraug Oct 21 '14 at 10:50
  • @carandraug Since `B = [1, 0, 0, 1, 0, 1]`, so `B==1` struck me as the first thing, but you are right about `~=0` for a general case. I was able to perform some related tests on these logical array issues and that I think confirm your quick tests too. These are posted here - http://stackoverflow.com/questions/25339215/is-a-0-really-better-than-a – Divakar Oct 21 '14 at 18:28