Calculation with strcmp with variable values

1 vue (au cours des 30 derniers jours)
Max Bornemann
Max Bornemann le 14 Avr 2019
Commenté : Max Bornemann le 16 Avr 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.

Réponse acceptée

A. Sawas
A. Sawas le 15 Avr 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 commentaires
A. Sawas
A. Sawas le 15 Avr 2019
Modifié(e) : A. Sawas le 15 Avr 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 le 16 Avr 2019
Thank you for the further advide. Can you give an example how it can be simplified?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by