2
votes

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']
2
Do you want C = ['a' '' 'c' '' 'e'] (which is the same as C='ace'), or do you want C = {'a' '' 'c' '' 'e'}? - Dan
@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
@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
i want the second option, i.e. C = {'a' '' 'c' '' 'e'} - user3270686

2 Answers

3
votes

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'
1
votes

Use logical indexing

C = B( A == 1 )