multiple linear regression check
6 次查看(过去 30 天)
显示 更早的评论
Hello Senior Matlab users
Firstly, I want to say sorry for my question as I am a beginner.
I want to ask for good programming advice for my messy code.
In my multiple linear regression example, there are two dependent variables( wind, temperature) and independent variable(evporation) for 10 numbers.
I got coefficients of beta1, beta2 and beta3 and I also checked the answer using calculated beta values. The answer seems correct.
The question is I used many for loops and I don't know how to code in only one for loop and smarter way. I also want to use built in regression function but don't know how to include.
So, if you can advice for my messy code, it would be very helpful for me.
Thank you very much.
clear all;clc;
data = csvread('multiregression.csv');
X = data(:,2:4);
wind= X(:,2);
temp= X(:,3);
Y = data(:,1);
Xt = data(:,2:4)';
Yt = data(:,1)';
beta= ((Xt*X)^-1)*(Xt*Y)
X2= size(X,1);
for i=1:X2
Xq(i)=beta(2)* wind(i);
end
for i=1:X2
Yq(i)= beta(3)*temp(i);
end
beta1= (beta(1)* ones(X2,1));
for i=1:X2
calculated_ans(i)= beta1(i) + Xq(i) + Yq(i);
end
answer= [calculated_ans' Y]
0 个评论
采纳的回答
Tommy
2020-4-14
All of the loops can be avoided. If you have something like
b=1:10;
for i=1:numel(b)
a(i)=2*b(i)+3;
end
you can always just use
b=1:10;
a=2*b+3;
instead, and MATLAB will apply the operations to each element within b. The following gives the same result as your code:
data = csvread('multiregression.csv');
Y = data(:,1);
X = data(:,2:4);
wind = X(:,2);
temp = X(:,3);
beta = X\Y;
calculated_ans = beta(1) + beta(2)*wind + beta(3)*temp;
answer = [calculated_ans Y];
beta = regress(X,Y);
but it would return the exact same thing as
beta = X\Y;
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Linear Regression 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!