- Technical Services and Consulting
- Embedded Systems | Firmware Developement | Simulations
- Electrical and Electronics Engineering
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?
14 次查看(过去 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.
0 个评论
采纳的回答
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);
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
Feel free to contact me.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!