Calculation with strcmp with variable values

3 ビュー (過去 30 日間)
Max Bornemann
Max Bornemann 2019 年 4 月 14 日
コメント済み: Max Bornemann 2019 年 4 月 16 日
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 Center および File ExchangeStructures についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by