Calculation with strcmp with variable values

조회 수: 1 (최근 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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by