Calculation with strcmp with variable values

1 Ansicht (letzte 30 Tage)
Max Bornemann
Max Bornemann am 14 Apr. 2019
Kommentiert: Max Bornemann am 16 Apr. 2019
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.

Akzeptierte Antwort

A. Sawas
A. Sawas am 15 Apr. 2019
[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 Kommentare
A. Sawas
A. Sawas am 15 Apr. 2019
Bearbeitet: A. Sawas am 15 Apr. 2019
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 am 16 Apr. 2019
Thank you for the further advide. Can you give an example how it can be simplified?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by