Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

regress(x,y) for least square regression of two variables x,y

Asked by mohamed

mohamed (view profile)

on 2 Jun 2013

when i use regress(x,y),I obtain only one answer :shouldn't i get two answers which are the slope and y-intercept ?

1 Comment

mohamed

mohamed (view profile)

on 2 Jun 2013

my code is x=[1 4 5 6];y=[4 6 7 9]

mohamed

mohamed (view profile)

Tags

2 Answers

Answer by the cyclist

the cyclist (view profile)

on 2 Jun 2013
Accepted answer

You don't show us your code, but I am guessing you neglected to add a column of ones to your x input, as described in the documentation:

doc regress

This code will give you the two-parameter output you expect:

x = [ones(3,1),rand(3,1)];
y = rand(3,1);
b = regress(y,x)

6 Comments

Image Analyst

Image Analyst (view profile)

on 2 Jun 2013

But I did answer that here. Did you ever look at where you first asked it?

the cyclist

the cyclist (view profile)

on 2 Jun 2013

@Image Analyst, I answered there, too, and did not realize it was the same poster! sigh

the cyclist

the cyclist (view profile)

on 2 Jun 2013
b = regress(z',[ones(4,1) x' y']);

combines x and y into one array, adds the column of ones that you need, and then does the regression with z.

the cyclist

the cyclist (view profile)

Answer by Image Analyst

Image Analyst (view profile)

on 2 Jun 2013

I don't have regress(). Please list what Product (toolbox) is is in below your question in the Product box.

You can use polyfit() which is in base MATLAB to get the slope and intercept in one line. Here's a full blown demo:

clc;
% Create training data:
x = [1 4 5 6]
y = [4 6 7 9]
% Do the regression.
coefficients = polyfit(x, y, 1); % 1 means a line
slope = coefficients(1)
intercept = coefficients(2)
% We're done!
% Plot training data:
plot(x, y, 'bo', 'LineWidth', 3);
hold on;
% Plot fit
numberOfPoints = 100;
fitX = linspace(min(x), max(x), numberOfPoints);
fitY = polyval(coefficients, fitX);
plot(fitX, fitY, 'r-', 'LineWidth', 3);
grid on;
xlabel('X', 'FontSize', 30);
ylabel('Y', 'FontSize', 30);

1 Comment

the cyclist

the cyclist (view profile)

on 2 Jun 2013

I always forget that regress() is not in core MATLAB. I added the Statistics Toolbox product tag.

Image Analyst

Image Analyst (view profile)

Contact us