Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: assign a number to a string
Replies: 2   Last Post: Dec 14, 2012 9:52 AM

 Messages: [ Previous | Next ]
 Steven Lord Posts: 18,038 Registered: 12/7/04
Re: assign a number to a string
Posted: Dec 14, 2012 9:52 AM

news:kaf36o\$9ja\$1@newscl01ah.mathworks.com...
> Dear all,
>
> I have a list of string:
>
> txt={'BBB3', 'BBB2', 'BBB1', 'A3', 'A2', 'A1','AA3','AA2','AA1'};
>
> i would like to assign a value to each string. For instance,

So you want to replace each string with a numeric value? That's easy.

> Here is my code
> for i=1:length(txt)
> if isequal(txt{'i'},'BBB3')

This attempts to check element double('i') [= 105] of txt to see if it is
equal to 'BBB3'. If you want to check if element i of txt is equal to
'BBB3', you need to say:

if isequal(txt{i}, 'BBB3')

> txt{'i'}=11;

I would recommend against making these changes in-place. Create a separate
numeric vector:

numericCodes = zeros(size(txt));

numericCodes(i) = 11;

*snip*

One way you can simplify this is to use STRCMP.

% Define the mapping data
stringsToMap = {'BBB3', 'BBB2', 'BBB1', 'A3', 'A2', 'A1','AA3','AA2','AA1'};
valuesToMap = [11, 12, 13, 14, 15, 16, 17, 18, 19];

% Define the data to be processed and the result
txt={'BBB3', 'BBB2', 'BBB1', 'A3', 'A2', 'junk', 'A1','AA3','AA2','AA1'};
numericCodes = repmat(20, size(txt)); % Since 20 is 'not present' we'll use
that to preallocate

% Do the work
for whichMap = 1:numel(stringsToMap)
% Find the matches
locateValues = strcmp(txt, stringsToMap{whichMap});

% Fill in the appropriate elements of numericCodes using the logical
numericCodes(locateValues) = valuesToMap(whichMap);
end

Your original code runs one loop iteration per element in txt and if that
cell array is large, that could take a good deal of time. This version
iterates over the strings for which you're checking, which I'm guessing is
smaller (perhaps MUCH smaller) than txt. It also avoids having to modify the
actual mapping code if you add a new string that needs to be mapped to a
value; instead you need to modify the mapping _data_. Note for example that
the code you posted doesn't have a case for 'AA1'; looking at the code I
posted it's trivial to check (by looking at stringsToMap and the
corresponding element of valuesToMap) that it will perform the mapping for
'AA1'.

--
Steve Lord
slord@mathworks.com
http://www.mathworks.com

Date Subject Author
12/14/12 bartekltg
12/14/12 Steven Lord