Linear fit over multiple Rows without using Loops (or polyfit)?

Hello, I have a matrix of data
I=[1.8,3,3.6,4.2,4.7,5.3,5.5;3.3,4.2,4.8,5.3,5.8,6.3,6.6;4.5,5.6,6.3,6.8,7.3,7.9,8.2;6.1,6.9,7.5,8,8.6,9,9.4]
I =
1.8000 3.0000 3.6000 4.2000 4.7000 5.3000 5.5000
3.3000 4.2000 4.8000 5.3000 5.8000 6.3000 6.6000
4.5000 5.6000 6.3000 6.8000 7.3000 7.9000 8.2000
6.1000 6.9000 7.5000 8.0000 8.6000 9.0000 9.4000
I would like to get the gradient of a straight line fit through each row.
i.e. I was just going to loop over all the rows something like this:
x = 1:7
1 2 3 4 5 6 7
y=I(1,:)
p=polyfit(x,y,1)
I then just want to average all those gradients (m's)
I was wondering if there was a better way to do this rather than use polyfit and loops?

 Respuesta aceptada

No, I don't think so. That way is fine.
I = [1.8,3,3.6,4.2,4.7,5.3,5.5;3.3,4.2,4.8,5.3,5.8,6.3,6.6;4.5,5.6,6.3,6.8,7.3,7.9,8.2;6.1,6.9,7.5,8,8.6,9,9.4]
I = 4×7
1.8000 3.0000 3.6000 4.2000 4.7000 5.3000 5.5000 3.3000 4.2000 4.8000 5.3000 5.8000 6.3000 6.6000 4.5000 5.6000 6.3000 6.8000 7.3000 7.9000 8.2000 6.1000 6.9000 7.5000 8.0000 8.6000 9.0000 9.4000
[rows, columns] = size(I)
rows = 4
columns = 7
x = 1 : columns;
coefficients = zeros(rows, 2);
for row = 1 : rows
coefficients(row, :) = polyfit(x, I(row, :), 1);
end
coefficients % Let's see them in the command window:
coefficients = 4×2
0.6000 1.6143 0.5393 3.0286 0.5964 4.2714 0.5429 5.7571
% Compute means
meanSlope = mean(coefficients(:, 1))
meanSlope = 0.5696
meanOffset = mean(coefficients(:, 2))
meanOffset = 3.6679

4 comentarios

Jason
Jason el 28 de Mzo. de 2022
Editada: Jason el 28 de Mzo. de 2022
I've been trying to see if Regress will work:
[y, x] = find(I)
B=reshape(I,1,[])
[x,y,B'] %View the matrix "unfolded"
scatter3(x,y,B','filled')
%Taken from the Regress help page
% https://uk.mathworks.com/help/stats/regress.html
X = [ones(size(x1)) x y x.*y]
b = regress(B',X)
x1fit = min(x):10:max(x);
x2fit = min(y):10:max(y);
YFIT = b(1) + b(2)*X1FIT + b(3)*X2FIT + b(4)*X1FIT.*X2FIT
mesh(X1FIT,X2FIT,YFIT)
But this mesh gives me an error:
Error using mesh
Z must be a matrix, not a scalar or vector.
Are you sure you replied to the correct thread?
Yes, sorry, this is also more of a visualisation part.
My mistake was this
x1fit = min(x):10:max(x);
should be this
x1fit = min(x):1:max(x);

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Get Started with Curve Fitting Toolbox en Centro de ayuda y File Exchange.

Productos

Versión

R2022a

Etiquetas

Preguntada:

el 28 de Mzo. de 2022

Comentada:

el 28 de Mzo. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by