I have two tables. How can I compare the values in the first column of each table, then do a calculation if the values are equal?

조회 수: 8 (최근 30일)
I imported data from two separate files. The data are stored in two separate tables. Each table contains columns of data. The first column is always "pressure." However, sometimes a particular pressure value is missing from one table. For example, Table 1 might be:
Pressure
1
2
3
4
5
while Table 2 is:
Pressure
1
3
4
5
6
I need to find out when the values in each table are the same (i.e., pressures of 1, 3, 4, and 5). Then I need to do a calculation that uses data from those rows and put the results in a third table.
I cannot figure out how to do this. I have tried:
for i=1:length(Table 2)
if Table1(i) == Table2(i)
Table3.append(Table1 .* 0.05) + (Table2 .* 0.95);
end
end
However, I get the error:
Arrays have incompatible sizes for this operation.
I would be grateful for any advice. Thank you.

채택된 답변

Hassaan
Hassaan 2024년 2월 17일
편집: Hassaan 2024년 2월 17일
@Srh Fwl A basic idea.
% Example initialization with an additional data column
Table1 = table([1; 2; 3; 4; 5], rand(5, 1), 'VariableNames', {'Pressure', 'DataColumn'});
Table2 = table([1; 3; 4; 5; 6], rand(5, 1), 'VariableNames', {'Pressure', 'DataColumn'});
% Find common 'Pressure' values
commonPressures = intersect(Table1.Pressure, Table2.Pressure);
% Initialize Table3 to store results
Table3 = table([], [], 'VariableNames', {'Pressure', 'Result'});
for i = 1:length(commonPressures)
% Find rows in each table that match the current pressure
rowInTable1 = Table1.Pressure == commonPressures(i);
rowInTable2 = Table2.Pressure == commonPressures(i);
% Use logical indexing to access the 'DataColumn' for calculations
result = (Table1.DataColumn(rowInTable1) * 0.05) + (Table2.DataColumn(rowInTable2) * 0.95);
% Append the common pressure and result to Table3
Table3 = [Table3; {commonPressures(i), result}];
end
% Display the result
disp(Table3);
Pressure Result ________ _______ 1 0.43724 3 0.558 4 0.4823 5 0.75785
DataColumn Added: The example assumes an additional column named 'DataColumn' exists in both tables for the calculation.
---------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
Feel free to contact me.
  댓글 수: 3

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Language Fundamentals에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by