How to find and replace an entire word in a cell array
1 view (last 30 days)
Show older comments
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!
0 Comments
Accepted Answer
Oleg Komarov
on 1 Aug 2012
Edited: Oleg Komarov
on 1 Aug 2012
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.
look = { 'b1' 33
'b22' 21
'b2' 44};
[idx, loc] = ismember(array1(2:end,2), look(:,1));
look(loc,2)
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!