# How to perform linear regression between respective columns of two matrix/table?

5 views (last 30 days)
Ranit on 20 Jan 2023
Commented: Star Strider on 23 Jan 2023
I have two matix/ table. For example,
Table 1:
Table 2:
I want to fit linear regression between respective columns of the two tables. For example, column 1 in Table 1 are y values. Column 1 in Table 2 are x values. I want to get slope and intercept of linear regression between these two columns. Then the same for column 2, 3 and so on. At the end I should have n different slope and intercept pair (suppose each table has total n columns) collected in a matrix or table.
P.S.:
Edit: I would also really like to know any approach without using a for loop.

Star Strider on 20 Jan 2023
One approach —
A1 = randn(5,10) % Y-Values
A1 = 5×10
0.0299 1.5214 0.3536 -1.1142 -0.1150 -0.5494 0.2548 -1.4189 1.0701 0.1450 -0.8383 1.7322 -0.2779 -1.0632 0.8443 0.0851 0.4722 -0.1375 -0.6431 0.4131 -0.8640 -1.6304 2.2374 -0.8050 1.1452 -0.2773 -0.4974 -1.6779 0.9647 0.7920 -1.8258 -1.1512 1.4659 -1.1022 0.8539 -0.0612 -0.3418 -0.0167 0.8839 -0.3638 0.3277 -0.3655 0.2634 0.7859 -2.1518 -1.2548 0.2227 -0.1939 -0.4167 -1.5957
A2 = randn(5,10) % X-Values
A2 = 5×10
0.3850 0.4773 1.2600 0.0907 -2.9750 0.4598 0.7622 -0.7591 -0.6958 0.8931 0.6983 -0.6295 0.4358 -1.0046 0.9418 0.5156 -1.1073 -0.2977 1.2468 -1.4143 0.6650 -0.4260 -0.1401 0.0958 -1.3038 -1.2276 -0.3434 -1.5117 0.3252 1.2938 -0.0940 -1.1737 0.9630 -1.8431 1.1628 -0.3611 0.3994 -0.5574 -0.6054 1.2328 1.1454 -1.2291 -1.3081 -0.2680 -0.6106 -0.1132 -0.3333 -0.9338 0.7663 0.4511
Rows = size(A1,1);
for k = 1:size(A1,2)
B(:,k) = [A2(:,k) ones(Rows,1)] \ A1(:,k);
end
Results = array2table(B.', 'VariableNames',{'Slope','Intercept'}, 'RowNames',compose('Col %4d',1:size(A1,2)))
Results = 10×2 table
Slope Intercept __________ _________ Col 1 1.4123 -1.4249 Col 2 1.1448 0.70382 Col 3 0.023978 0.80266 Col 4 0.27999 -0.49571 Col 5 0.19567 0.2243 Col 6 -0.0015634 -0.41174 Col 7 -0.16755 0.0012506 Col 8 1.2526 0.32805 Col 9 -0.85766 0.54969 Col 10 -0.059937 -0.092407
.
##### 2 CommentsShowHide 1 older comment
Star Strider on 23 Jan 2023
As always, my pleasure!

### Categories

Find more on Descriptive Statistics in Help Center and File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!