Finding cells with specific string in cell array and substituting them

In a cell array named CC I search for a specific string, ' -' and I want to substitute the contents of all those cells with something else, e.g. '0'. When I perform the search using
[ii jj]=find(strncmpi(CC,' -',2))
I get the resulots in the form:
ii= 1
2
3
4
8
and
jj= 12
12
12
15
15
Now: how can I change the elements containg that string and having indexes ii & jj with '0'? I tried different form but cannot find a way to refer to elements of CC having ii & jj as row and column number.

 채택된 답변

You can simply use strrep to replace strings in a cell array:
CC = {'A',' -','B',' -','C'}
CCout = strrep(CC,' -', '0')

댓글 수: 2

Thanks Jos,
what you suggested seems like a very fast solution, but MATLAB gave me the error message:
Cell elements must be character vectors.
when I tried it.
My data is based on excel input of the cell type but somewhere in the original excel file there are some blank columns that have been replaced with a ' -' string in the original format (see picture below) and whnever I want to turn the entire dataset to a numerical array using cell2mat then I see the error message that data types should be the same.
Ah, your cell is a mixture of strings and numbers ...
CC(strcmpi(CC,' -')) = {0}

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Stephen23
Stephen23 2017년 12월 19일
Using find is not required, and just makes it much more complex. All you need is to use logical indexing:
idx = strncmpi(CC,' -',2);
CC(idx) = {'0'};

댓글 수: 4

Thanks Stepehen, but in the output forat the result still looks like '0' and not [0], and I still get an error trying to turn the whole thing to a numerical array.
cell2mat(CC)
Error using cell2mat (line 45)
All contents of the input cell array must be of the same data type.
Nevermind, I guess I just had to replace {'0'} with {[0]}!!! Thanks anayway!
Putting a scalar numeric into square brackets is pointless. All you need is simply {0}.
Thanks Stepehn, I changed that!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2017년 12월 19일

댓글:

2017년 12월 20일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by