4

I have an array of numbers in MATLAB eg.,

a = [1 1 1; 2 2 1; 3 3 2; 4 5 1];

and I would like to replace the numbers with strings.

eg., 1= "apples"; 2= "hello"; 3 = "goodbye";

I can for example replace with other numbers eg.,

a(a==1) = 999
a(a==2) = 998

but I need to accomplish the same kind of thing by replacing with string. Not easy to me can someone help me out ? Thanks, Matilde

0

3 Answers 3

5

In case your numbers always start with 1 and every number should be replaced, that's just indexing:

>> mp={'apples','hello','goodby'}

mp = 

    'apples'    'hello'    'goodby'

>> a = [1 1 1; 2 2 1; 3 3 2]

a =

     1     1     1
     2     2     1
     3     3     2

>> mp(a)

ans = 

    'apples'    'apples'    'apples'
    'hello'     'hello'     'apples'
    'goodby'    'goodby'    'hello' 
Sign up to request clarification or add additional context in comments.

Comments

3

This could be one approach to handle mixed data of strings and numbers for a cell array output -

%// Numeric array and cell array of input strings 
a = [1 1 1; 2 2 1; 3 3 2; 4 5 1];
names = {'apples','hello','goodbye'}

%// Create a cell array to store the mixed data of numeric and string data 
a_cell = num2cell(a)

%// Get the mask where the numbers 1,2,3 are which are to be replaced by
%// corresponding strings
mask = ismember(a,[1 2 3])

%// Insert the strings into the masked region of a_cell
a_cell(mask) = names(a(mask))

Code run -

a =
     1     1     1
     2     2     1
     3     3     2
     4     5     1
names = 
    'apples'    'hello'    'goodbye'
a_cell = 
    'apples'     'apples'     'apples'
    'hello'      'hello'      'apples'
    'goodbye'    'goodbye'    'hello' 
    [      4]    [      5]    'apples'

2 Comments

Last line could be replaced with a_cell(mask)=names(a(mask)) to simplify.
@Daniel Just did actually :)
0

I don't know, if you really want to replace the values or create a new array of the same size with the strings in it. As the others pointed out, you need a cell array to store the strings.

a = [1 1 1; 2 2 1; 3 3 2; 4 5 1];
aStrings = cell(3,4)
aStrings(a==1) = {'apples'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.