There are multiple issues with your code, but they all boil down to the superfluous looping over rows and columns. Doing so means polyfit is applied to scalar values, which is totally useless.
Try this instead:
A = [0.5 0.2 1; 0.6 1.2 1; 0.3 0.23 1; 0.52 0.64 2; 0.56 0.7 2]
X = accumarray(A(:,3),A(:,1),[],@(v){v})
Y = accumarray(A(:,3),A(:,2),[],@(v){v})
C = cellfun(@(x,y)polyfit(x,y,1),X,Y,'UniformOutput',false);
this gives the points fitted in cell arrays X and Y, and the fitted polyfit output (coefficients) in the cell array C. For the example data, it gives these coefficients: >> C{:}
ans =
2.75000 -0.74000
ans =
1.50000 -0.14000
Plot in a Loop
I also plotted these coefficients and the original data, to check them:
F = 'rg';
V = 0:0.01:1;
for k = 1:numel(C)
plot(X{k},Y{k},['o',F(k)])
hold on
plot(V,polyval(C{k},V),F(k))
end
Plot at Once
You could also plot it without any (explicit) loop:
V = 0:0.01:1;
Z = [X,Y]';
Z(3,:) = {'o'};
plot(Z{:})
hold on
W(2,:) = cellfun(@(c)polyval(c,V),C,'UniformOutput',false);
W(1,:) = {V};
plot(W{:})
This has the advantage that it uses the axes/figure ColorOrder property, so you do not need to specify the colors yourself: