2

I use MATLAB and I have to make the following pairing:

I have an array with integers:

A = [1 0 1 0 1] 

and an array of the same dimension, with strings:

B = ['a' 'b' 'c' 'd' 'e']

I need to create a string array, C, where for every element of matrix A that is 0 the corresponding element of matrix C is blank ('') but for every element of matrix A that is 1, the corresponding element of matrix C is equal with the corresponding element of B.

i.e. the array C would be :

C = ['a' '' 'c' '' 'e']
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
  • Repeated: http://stackoverflow.com/questions/22043110/map-a-matrix-with-another-matrix/22043212#22043212 – tashuhka Feb 27 '14 at 14:48
  • 1
    Do you want `C = ['a' '' 'c' '' 'e']` (which is the same as `C='ace'`), or do you want `C = {'a' '' 'c' '' 'e'}`? – Dan Feb 27 '14 at 14:49
  • @tashuhka, do you want to mark this as a duplicate question? I'm not sure it is, since this is for strings and that qeustion was for integers. – pattivacek Feb 27 '14 at 14:52
  • @patrickvacek. You have more experience than me to know what can be considered duplicate and what cannot. I just saw that logical indexing was partially covered in the mentioned link. – tashuhka Feb 27 '14 at 14:56
  • i want the second option, i.e. C = {'a' '' 'c' '' 'e'} – user3270686 Feb 27 '14 at 14:57
  • @tashuhka, no problem! They are similar, but I think they are different enough to exist independently. They could be generalized into one solution, but probably not if the empty strings need to be represented. – pattivacek Feb 27 '14 at 14:58
  • @patrickvacek. I agree :) – tashuhka Feb 27 '14 at 15:01

2 Answers2

3

If you define B as a cell array makes more sense:

B = {'a' 'b' 'c' 'd' 'e'}

then assign empties like so:

>> B(A==0) = {''}
B = 
   'a'    ''    'c'    ''    'e'
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
1

Use logical indexing

C = B( A == 1 )
Shai
  • 111,146
  • 38
  • 238
  • 371