How to find and replace an entire word in a cell array
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Oleg Komarov
2012 年 8 月 1 日
編集済み: Oleg Komarov
2012 年 8 月 1 日
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)
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Cell Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!