user3270686
user3270686

Reputation: 81

assign strings into matrix elements

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']

Upvotes: 2

Views: 242

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

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'

Upvotes: 3

Shai
Shai

Reputation: 114796

Use logical indexing

C = B( A == 1 )

Upvotes: 1

Related Questions