multiple linear regression check

4 views (last 30 days)
soe thiha
soe thiha on 14 Apr 2020
Commented: soe thiha on 14 Apr 2020
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]

Accepted Answer

Tommy
Tommy on 14 Apr 2020
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];
You could use the MATLAB function regress, like so
beta = regress(X,Y);
but it would return the exact same thing as
beta = X\Y;
  1 Comment
soe thiha
soe thiha on 14 Apr 2020
Hello Tommy
Thank you very much for your suggestion and it is really helpful for me.
Regards,

Sign in to comment.

More Answers (0)

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!