MATLAB:存储在矩阵中的数据的线性回归(用于循环?)
我尝试对存储在多个矩阵(MATLAB)中的数据进行线性回归。对于向量,线性回归非常简单:
%x-values
x = [1.5;2.5;5]; %x-vector
%y-values
y = [9;11.1;17]; %y-vector
%Regression:
X = [ones(length(x),1) x] %Matrix to do the backslash calculation--> how can I set that up if I have a matrix for x and not a vector?
m2 = X\y; %backslash calculation --> first value: intercept, second value: slope
yCalc = X*m2; %linear regression
Rsq2 = 1 - sum((y - yCalc).^2)/sum((y - mean(y)).^2); %R² value
在我的情况下,x-和y-data存储在矩阵中:
X = [a1 b1 c1;
a2 b2 c2;
a3 b3 c3]
Y = [A1 B1 C1;
A2 B2 C2;
A3 B3 C3]
必须在矩阵x(x-values:a1 a2 a3)和矩阵y的第一列(相应的y值:A1 A2 A3),然后以所有其他列的方式(2 ... i )。我已经尝试了几种不同的方法(主要是横面)。最后,我总是弄乱设置1 ... i 矩阵,其中包含第一列中的矩阵和第1列的x-data ... i (矩阵x)在第二列中运行后斜线操作,这是获得回归的截距和斜率所需的。最后,我想为我所做的每一次回归存储变量M2,YCALC和RSQ2。谁能帮忙?那将非常有帮助!非常感谢!
I try to do a linear regression for data that is stored in several matrices (Matlab). For vectors, the linear regression is pretty straight forward:
%x-values
x = [1.5;2.5;5]; %x-vector
%y-values
y = [9;11.1;17]; %y-vector
%Regression:
X = [ones(length(x),1) x] %Matrix to do the backslash calculation--> how can I set that up if I have a matrix for x and not a vector?
m2 = X\y; %backslash calculation --> first value: intercept, second value: slope
yCalc = X*m2; %linear regression
Rsq2 = 1 - sum((y - yCalc).^2)/sum((y - mean(y)).^2); %R² value
In my case the x- and y-data is stored in matrices:
X = [a1 b1 c1;
a2 b2 c2;
a3 b3 c3]
Y = [A1 B1 C1;
A2 B2 C2;
A3 B3 C3]
The linear regression has to be done between the first column in matrix X (x-values: a1 a2 a3) and the first column of matrix Y (respective y-values: A1 A2 A3) and then for all the other columns in the same way (2...i). I already tried a couple of different approaches (mainly for-loops). In the end, I always mess up with setting up 1...i matrices that contain ones in the first column and the x-data of column 1...i (Matrix X) in the second column to run the backslash operation which is needed to obtain the intercept and slope for the regression. IN the end, I would like to store the variables m2,yCalc and Rsq2 for every regression that I did. Can anyone help? That would be very helpful! Many thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用函数文件以组织您的程序。放入
文件
lin_reg.m
中。所有lin_reg
从脚本输出
Use a function file to organize your program. Put
in a file
lin_reg.m
. Сalllin_reg
from a scriptoutputs