MATLAB Answers

0

How replace matching string

Asked by Mekala balaji on 12 Jun 2019
Latest activity Commented on by Stephen Cobeldick on 28 Jun 2019
Hi,
I have below cell array:
Pass Pass{overflow :1,unbound:5,warning:9} Miss
Pass Miss Trigger
Passs Pass Pass
I want to replace:
  1. Pass with '1',
  2. Miss with '2' ,
  3. Any thing else with '2'
Kindly some one help how to do this,
I can only strrep to replace, I dont not know how to do 3rd condition(any thing else)

  0 Comments

Sign in to comment.

1 Answer

Rik
Answer by Rik
on 12 Jun 2019
Edited by Rik
on 12 Jun 2019

Because your second and third condition can be merged, you can use ismember:
data={'Pass','Pass{overflow :1,unbound:5,warning:9}','Miss';
'Pass','Miss','Trigger';
'Passs','Pass','Pass'};
L=ismember(data,{'Pass'});
output=2*ones(size(data));
output(L)=1;
Note that this requires exact matches. You could also write a custom function and use cellfun:
output2=cellfun(@my_custom_fun,data)
function val=my_custom_fun(str)
if strcmpi(str,'pass')
val=1;
elseif strcmpi(str,'miss')
val=2;
elseif contains(str,'Pass')
val=1.5;
else
val=2;
end
end

  3 Comments

Rik
on 22 Jun 2019
Did this suggestion solve your problem? If so, please consider marking it as accepted answer. It will make it easier for other people with the same question to find an answer. If this didn't solve your question, please comment with what problems you are still having.
It giving me error,
Error using cellfun
Undefined function 'my_custom_fun' for input arguments of type 'char'.
@Mekala balaji: did you copy the function that Rik gave you, and save it to your Search Path (e.g. the current directory) using that function name?

Sign in to comment.