MATLAB: Polyfit not working right

2d plotsMATLABpolyfit

Hello everyone!
So, Ive been working on a code that will allow me to seperate five cycles of stress and strain (Mechanics of materials). There a five cycles of loading and unloading. My code is as follows;
g=0;
Cycle1UpStop=1;
A=[5 5];
h=0;
while (A(1,1)>0) & (h<0.3)
h = AverageStrain(1+g:60+g,:);
i = AverageStress(1+g:60+g,:);
A = polyfit(h,i,1);
Cycle1UpStop = g+30;
g = g+60;
end
Cycle1UpStrain=AverageStrain(1:Cycle1UpStop,1);
Cycle1UpStress=AverageStress(1:Cycle1UpStop,1);
plot (Cycle1UpStrain, Cycle1UpStress);
The problem I'm having is that the last result in the polyfit SHOULD have the first value as a 0 or negative, to represent the slope, right? Well, every time I run the program, the coefficient of A on the first column where the slope should be usually turns out something ridiculous like 571. Positive and far from zero…
On the same note, my graph seem to cut off somewhat close to where the slope is indeed zero, but still somewhat positive. I've tried changing the amount of points it takes in order to fit a straight line to it.
Edit:
AverageStress and AverageStrain are variable of 1785×1 matrix. I use them as my X and Y data if I want to plot all five cycles.
Attached is the resulting plots I get (the code given is my attempt for the FIRST TWO PLOTS). I want the cycle to end AT THE TIP indicated in the red circle. (or very close to it)
Thanks for your time and aid!
Neil

Best Answer

The vector logic for ‘h < 0.3’ as written will fail, and will never evaluate to true.
Example:
h = rand(1,25) % Generate ‘h’

logic = h < 0.3 % Logical vector showing ‘1’ for values: h < 0.3

if h < 0.3 % If true then say so
disp('TRUE!')
end
The ‘if’ condition is never satisfied, and the message never prints.
However, with one change (add ‘any’) to the condition in the if block:
h = rand(1,25) % Generate ‘h’
logic = h < 0.3 % Logical vector showing ‘1’ for values: h < 0.3
if any(h < 0.3) % If any are true then say so
disp('TRUE!')
end
produces:
TRUE!