How can I compare strings and create a new column with the comparison result?
1 view (last 30 days)
Show older comments
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 Comment
Jan
on 25 Oct 2016
I've formatted the code. Please use the "{} code" button to provide readable code. Thanks.
Accepted Answer
Jan
on 25 Oct 2016
Edited: Jan
on 25 Oct 2016
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 Comments
Guillaume
on 25 Oct 2016
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);
More Answers (0)
See Also
Categories
Find more on Author Block Masks in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!