Calculation with strcmp with variable values

2 次查看(过去 30 天)
Hello,
I have the following three tables:
Tab1=table('Size',[9 3],'VariableTypes',{'cell','double','double'},'VariableNames',{'Description','Year','Value'});
Tab1.Description(:)={'Gas','Gas','Gas','Pellets','Pellets','Pellets','Oil','Oil','Oil'};
Tab1.Year(:)=[2015,2020,2025,2015,2020,2025,2015,2020,2025];
Tab1.Value(:)=[5,10,17,7,25,75,23,47,54];
Tab2=table('Size',[6 3],'VariableTypes',{'cell','double','double'},'VariableNames',{'Description','Year','Value'});
Tab2.Description(:)={'Gas','Gas','Gas','Oil','Oil','Oil'};
Tab2.Year(:)=[2015,2020,2025,2015,2020,2025];
Tab3=table('Size',[3 2],'VariableTypes',{'double','double'},'VariableNames',{'Year','Value'});
Tab3.Year(:)=[2015,2020,2025];
Tab3.Value(:)=[1002,3007,2001];
I am searching for a way, to simplify the following calculation:
for i=1:3
Tab2{strcmp(Tab2.Description,'Gas'),'Value'}(i)=Tab1{strcmp(Tab1.Description,'Gas'),'Value'}(i)*Tab3{i,'Value'};
Tab2{strcmp(Tab2.Description,'Oil'),'Value'}(i)=Tab1{strcmp(Tab1.Description,'Oil'),'Value'}(i)*Tab3{i,'Value'};
end
clear i;
Imagine Tab1 and Tab2 are way bigger and there are way more different Values in the "Description"-column, then the solution above would be inappropriate.
I thought about something like:
for i=1:3
Tab2{strcmp(Tab2.Description,'X'),'Value'}(i)=Tab1{strcmp(Tab1.Description,'X'),'Value'}(i)*Tab3{i,'Value'};
end
clear i;
where X can have all the different Descriptions from Tab2. But i don´t know how to do it in MATLAB.
I will greatly appreciate any assistance.

采纳的回答

A. Sawas
A. Sawas 2019-4-15
[C,idx1,idx2] = innerjoin(Tab1,Tab2, "LeftKeys",{'Description','Year'},"RightKeys",{'Description','Year'});
[~,idx3] = join(C, Tab3, "Keys","Year");
Tab2.Value(idx2) = Tab1.Value(idx1).*Tab3.Value(idx3);
  3 个评论
A. Sawas
A. Sawas 2019-4-15
编辑:A. Sawas 2019-4-15
My pleasure!
I want to add that the steps can be simplified if you are generating Tab2 from Tab1. Hence, in the above solution, the inner join is needed assuming those tables are different but have two common variables.
Max Bornemann
Max Bornemann 2019-4-16
Thank you for the further advide. Can you give an example how it can be simplified?

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by