# How to find and replace an entire word in a cell array

Asked by Manfred on 1 Aug 2012
Latest activity Commented on by Manfred on 9 Aug 2012

I am new to Matlab, so pardon my ignorance...

I have imported a .csv file into Matlab which is a mix of text and numbers.

array1=

```    'h1'    'h2'
[ 1]    'b1'
[ 2]    'b2'
[ 3]    'b22'
[ 4]    'b2'   ```

I would like to replace text in 2nd column by numbers. I have created an array which only contains the 2nd column array2=array1(:,2) and created a List = (b1; b2;b22) which contains elements of array2 which should be replaced by Replace(1;2;3):

function data = text2num(Matrix, List, Replace)

data=strrep(array2, List(1,1) , Replace(1,1))

for i=2 : numel(List)

data=strrep(data, List(i,1), Replace(i,1))

end

However, this ends up replacing 'b22' with '22', instead of '3', since it searches for 'b2' first and replaces the first two letters of b22 with 2, and leaves the third letter (2), which adds up to 22.

Hope this makes sense. Any hint where to search for would be appreciated. Thanks!

## Products

No products are associated with this question.

Answer by Oleg Komarov on 1 Aug 2012
Edited by Oleg Komarov on 1 Aug 2012

In this case you can simply use unique

```array1 = {'h1'   'h2'
1    'b1'
2    'b2'
3    'b22'
4    'b2'   };
```
```[un,trash,rep] = unique(array1(2:end,2));
```

This works because unique returns a vector with unique values in sorted order and it assigns an increasing index which is returned for each value in rep.

However, a more general case will use ismember (which adapts to custom lookup matching):

```look = { 'b1'  33
'b22' 21
'b2'  44};
```
```[idx, loc] = ismember(array1(2:end,2), look(:,1));
look(loc,2)
```

## 1 Comment

Manfred on 9 Aug 2012

Many thanks for the fast and useful reply!