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?

21 次查看(过去 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