compare two strings of cell array at different length and replace the existing string with a new set of strings

I need to check the elements of A and if the elements of A contains elements of B. I need to replace the elements of A with the elements of C only if the element of B is present in A.
I have three sets of cell array strings of different length as follows:
>> A={'apple';'ant';'book';'apple';'boy';'apple';'ant'};
>> B={'apple';'ant';'book'};
>> C={'apple1';'ant1';'book1'};
I need to check whether the elements of B are used in the elements of A. I have used several MATLAB inbuilt functions to check the elements but, I am not able to obtain the expected output. So, I am comparing strings of A and B with the following code:
X = zeros(size(A));
for i = 1:numel(B)
X(strncmp(A,B{i},3)) = i;
end
Here, I am getting the output of X as
X =
1
2
3
1
0
1
2
Now, I need to check the elements of A and if the elements of A contains elements of B. I need to replace the elements of A with the elements of C only if the element of B is present in A.
Here, I am getting the position of each element of B but not the logical indices of A. In simpler words, I need the output in the form of 1's and 0's. So, that I can replace the elements of A with the elements of C

 Akzeptierte Antwort

Use regexprep and this task is simple:
>> A = {'apple';'ant';'book';'apple';'boy';'apple';'ant'};
>> B = {'apple';'ant';'book'};
>> C = {'apple1';'ant1';'book1'};
>> Z = regexprep(A,B,C);
>> Z{:}
ans = apple1
ans = ant1
ans = book1
ans = apple1
ans = boy
ans = apple1
ans = ant1
Or if you want to be more robust:
Brgx = strcat('^',regexptranslate('escape',B),'$');
Z = regexprep(A,Brgx,C);

2 Kommentare

Thank you for your answer Stephen. I have one more doubt. Without replacing the elements directly, is it possible to ask a user (by using msgbox or questdlg functions) whether to replace the element or not? If he says yes, the element has to be replaced or if it is no, the existing element need to be retained.
Sure, just use the message box to define some indices, and select the pattern and replacement cell array subsets using those indices.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-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