MATLAB Answers

strcmp with or-condition

12 views (last 30 days)
i have the following two tables:
Tab1=table('Size',[9 3],'VariableTypes',{'cell','double','double'},'VariableNames',{'Description','Year','Value'});
Tab2=table('Size',[6 3],'VariableTypes',{'cell','double','double'},'VariableNames',{'Description','Year','Value'});
I try the following calculation:
The or-part seems to be the problem. I want the Value of 'FW' from Tab2 as the Value of 'Gas' and 'Oil' in Tab1. My original table is way bigger, so seperate calculations like:
are not purposeful. Maybe an if-condition with
could help, but i dont know how.
I will greatly appreciate any assistance.
Max Bornemann
Max Bornemann on 16 Apr 2019
Can someone help?

Sign in to comment.

Accepted Answer

Ben Cunningham
Ben Cunningham on 16 Apr 2019
Edited: Ben Cunningham on 16 Apr 2019
Generally I would recommend just writing out two lines as Adam proposed earlier.
But if you really want 'one line' with a list of strings to index then you could wrap it in a for loop :
for DescriptionIndex = {'Gas', 'Oil'}, Tab1(strcmp(Tab1.Description, DescriptionIndex),'Value')=Tab2(strcmp(Tab2.Description,'FW'),'Value'); end
Ben Cunningham
Ben Cunningham on 23 Apr 2019
Well found!
If you are doing this mulitiple times you might consider putting this code in a nicely named function which may help it look clearer.
(Name the function something that makes sense for what you are doing - also the variables might benefit from clearer names).
e.g. At the end of your script :
function TabOut = myFunctionName (Tab1, Tab2, Tab3, Sum)
% My Function does something
for Sum1 = Sum
TabOut = Tab2;
Then in your script you can write :
Tab2 = myFunctionName (Tab1, Tab2, Tab3, {'Pellets','Oil','Heatpump';'Wood','HeatingOil','Heat'})

Sign in to comment.

More Answers (1)

Adam Danz
Adam Danz on 16 Apr 2019
Edited: Adam Danz on 16 Apr 2019
You would use ismember() to find the rows of Tab1.Description that match a list of options.
ismember(Tab1.Description, {'Gas', 'Oil'})
However, you'll find out that this matches 6 rows but the data on the right hand side of the equal sign only produces 3 rows.
What I think you're trying to do is to assign those 3 values to all rows in Tab1 that are labeled 'Gas' and to assign those 3 values to all rows labeled 'Oil', too.
Ben Cunningham
Ben Cunningham on 16 Apr 2019
Aye that's right.

Sign in to comment.


Community Treasure Hunt

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

Start Hunting!