フィルターのクリア

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

2 ビュー (過去 30 日間)
Eduardo Rocha
Eduardo Rocha 2016 年 10 月 24 日
コメント済み: Eduardo Rocha 2016 年 10 月 25 日
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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by