필터 지우기
필터 지우기

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

조회 수: 2 (최근 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);
  댓글 수: 1
Jan
Jan 2016년 10월 25일
I've formatted the code. Please use the "{} code" button to provide readable code. Thanks.

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

채택된 답변

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);
Eduardo Rocha
Eduardo Rocha 2016년 10월 25일
Thank you, now its easier to understand and the code works perfectly :)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by