Conditionally Flip Sign in Table

2 views (last 30 days)
I have a very simple question. Based on a matrix like this one:
A = [repmat({'Yes'},3,1) , repmat({'2'},3,1); repmat({'No'},3,1) , repmat({'2'},3,1)];
I want to flip the sign of column 2 if the entry in colum one is 'No', but leave it as is if the entry in colun one is 'Yes'.
The result should be the following:
B = [repmat({'Yes'},3,1) , repmat({'2'},3,1); repmat({'No'},3,1) , repmat({'-2'},3,1)];
I suppose I can do this using one line of code using cellfun, but I am not sure what is the most optimized way.
Thx for your help!

Accepted Answer

Matt Tearle
Matt Tearle on 4 Nov 2014
Edited: Matt Tearle on 4 Nov 2014
One liner:
A(strcmp(A(:,1),'No'),2) = strcat('-',A(strcmp(A(:,1),'No'),2))
Slightly cleaner with two lines:
idx = strcmp(A(:,1),'No');
A(idx,2) = strcat('-',A(idx,2))
But... if you're worrying about efficiency, I'd want to know if A has to be in the form it is. Does the second column have to text, rather than numeric?
And do you have 13b or later (or Statistics TB)? Because I think you might have an easier time using tables and categoricals. For example:
% Make a table version of A
Atable = cell2table(A,'VariableNames',{'YesOrNo','Number'})
% Convert strings to categories and string numbers to actual numbers
Atable.YesOrNo = categorical(Atable.YesOrNo)
Atable.Number = str2double(Atable.Number)
% Now, do the sign flipping
Atable.Number(Atable.YesOrNo == 'No') = -Atable.Number(Atable.YesOrNo == 'No')
  6 Comments
Federico Canè
Federico Canè on 4 Nov 2014
This works like a charm. Thx! :)

Sign in to comment.

More Answers (0)

Categories

Find more on Tables 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!