# How can I search a cell array for all instances of a character and replace it with something else?

3 Ansichten (letzte 30 Tage)
Andreea Juravschi am 29 Okt. 2019
Beantwortet: Rik am 29 Okt. 2019
Hi there!
I created a cell array that contains doubles with the occasional '*' as a space holder in some of the locations within the cell array itself. i need to find the astericks, and replace it with the average of the doubles above and below the astericks. I'm not sure how to go about searching for the astericks within a cell array?
Thank you!!
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Antworten (2)

Jos (10584) am 29 Okt. 2019
Something along these lines, perhaps?
C = {1.1 pi '*' ; 3 '*' 2.2}
tf = cellfun(@(x) isequal(x,'*'), C)
idx = find(tf)
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

Rik am 29 Okt. 2019
From your description, I suspect the simple fact that it is an asterisk doesn't actually matter. The code below will find all cell positions where there is a char and replace them by NaN. Then you have three options: loop through all indices you found, do some clever indexing, or replicate a shifted array. I went with the third (the first is easiest to implement boundary conditions, the second should scale best for large arrays, and the third is a bit of a middle ground).
clc
C = {1.1 pi '*' ; 3 '*' 2.2 ; 1 5 9};
tf = cellfun('isclass', C,'char');
C(tf)={NaN};
A=cell2mat(C)
[r,c]=find(tf);
A_row_shift_up= circshift(A,-1,1);
A_row_shift_up(end,:)=NaN;%blank out the bottom line
A_row_shift_down=circshift(A, 1,1);
A_row_shift_down(1,:)=NaN;%blank out the top line
A(tf)=mean(cat(3,A_row_shift_up(tf),A_row_shift_down(tf)),3,'omitnan')
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by