How can I compare strings and create a new column with the comparison result?

1 次查看(过去 30 天)
I have "cat1" and "cat2" that are 2 columns with strings:
If cat1 is low and cat2 is low, I want cat3 to be '1'; If cat1 is medium low and cat2 is medium low, I want cat3 to be '2'; And so on until high and high. If none of these conditions are satisfied, I want cat3 to be '0';
How can I do this? I tried this way but it says "Undefined operator '==' for input arguments of type 'cell'" :
teste1 = repmat( {''}, length(catpreco(:,1)), 1);
mask = catpreco(:,1) == 'low' & catconsumo(:,1)== 'low';
catpreco(mask) = cellfun(@(S) [S, '1'], catpreco(mask), 'Uniform', 0);
mask = catpreco(:,1) == 'medium low' & catconsumo(:,1)== 'medium low';
catpreco(mask) = cellfun(@(S) [S, '2'], catpreco(mask), 'Uniform', 0);
mask = catpreco(:,1) == 'medium' & catconsumo(:,1)== 'medium';
catpreco(mask) = cellfun(@(S) [S, '3'], catpreco(mask), 'Uniform', 0);
mask = catpreco(:,1) == 'medium high' & catconsumo(:,1)== 'medium high';
catpreco(mask) = cellfun(@(S) [S, '4'], catpreco(mask), 'Uniform', 0);
mask = catpreco(:,1) == 'high' & catconsumo(:,1)== 'high';
catpreco(mask) = cellfun(@(S) [S, '5'], catpreco(mask), 'Uniform', 0);

采纳的回答

Jan
Jan 2016-10-25
编辑:Jan 2016-10-25
The error message means, that you cannot compare a cell array with a string using the == operator. Use strcmp instead:
cat3 = cell(size(cat1));
cat3(:) = {'0'};
mask = strcmp(cat1, 'low') & strcmp(cat2, 'low');
cat3(mask) = {'1'};
mask = strcmp(cat1, 'medium low') & strcmp(cat2, 'medium low');
cat3(mask) = {'2'};
mask = strcmp(cat1, 'medium') & strcmp(cat2, 'medium');
cat3(mask) = {'3'};
mask = strcmp(cat1, 'medium high') & strcmp(cat2, 'medium high');
cat3(mask) = {'4'};
mask = strcmp(cat1, 'high') & strcmp(cat2, 'high');
cat3(mask) = {'5'};
A loop might be nicer:
list = {'low', 'medium low', 'medium', 'medium high', 'high'};
for k = 1:5
mask = strcmp(cat1, list{k}) & strcmp(cat2, list{k}));
cat3(mask) = {sprintf('%d', k)};
end
  2 个评论
Guillaume
Guillaume 2016-10-25
Even simpler (no loop):
list = {'low', 'medium low', 'medium', 'medium high', 'high'};
cat3 = zeros(size(cat1));
[~, cat1result] = ismember(cat1, list);
[~, cat2result] = ismember(cat2, list);
cat3(cat1result == cat2result) = cat1result(cat1result == cat2result);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Author Block Masks 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by