Matlab / Simulink polyfit - matlab

I want to fit the second degree equation to the graph like shows.
I have already "From workspace" blocks and "Scope" blocks
.
Now my problem is how do I fit second degree graph. I have already "constant" block where I have "cars" matrix. Then I have "ramp" block which creates slope between 1-365 like shows.
Then I have "Least Squares Polynomial Fit" and "Polynomial Evaluation" blocks . What I am doing wrong because it isn't working?
This is my matlab code:
n = importdata('n.txt',';')
cars = n(:,2)
trucks = n(:,3)
bus = n(:,4)
t = linspace(1,365,365)
t = transpose(t)
It gives me error "Error in port widths or dimensions. Output port 1 of .. is a [32x3] matrix." and "The number of rows of input A must match the number of rows of input B."

Given the model you show, I assume you have looked at the example for the Least Square Polynomial Fit block, and completely misunderstood what it is doing.
It is showing an example where the coefficients of a polynomial as a function of time are known, then using the Polynomial Evaluation block to evaluate the polynomial, then using the Least Square Polynomial Fit to get the coefficients of the polynomial back again. That is, it is showing that when data is "round tripped" though both blocks you get back to where you started, supposedly giving you confidence that the blocks are "doing the right thing".
But what they show is not what you are wanting to do, and hence you need a different model.
If you look at the documentation for the Polynomial Evaluation block, there are several examples of what the inputs are expected to be.
The first input is the independent variable, which in your case appears as if it should be simulation time. You can use a Ramp for this, but why not just use the Clock block. (If you do use a Ramp then you want it to have an Initial Value of 0, not 365 as you show in the image in your question.)
The second input are the coefficients of the polynomial as a vector. These could be pregenerated (using for instance MATLAB's polyfit) function, or could be generated on the fly using the Least Square Polynomial Fit block.
That is, it looks like you really want the following model:

Related

MATLAB: polyval function for N greater than 1

I am trying trying to graph the polynomial fit of a 2D dataset in Matlab.
This is what I tried:
rawTable = readtable('Test_data.xlsx','Sheet','Sheet1');
x = rawTable.A;
y = rawTable.B;
figure(1)
scatter(x,y)
c = polyfit(x,y,2);
y_fitted = polyval(c,x);
hold on
plot(x,y_fitted,'r','LineWidth',2)
rawTable.A and rawTable.A are randomly generated numbers. (i.e. the x dataset cannot be represented in the following form : x=0:0.1:100)
The result:
second-order polynomial
But the result I expect looks like this (generated in Excel):
enter image description here
How can I graph the second-order polynomial fit in MATLAB?
I sense some confusion regarding what the output of each of those Matlab function mean. So I'll clarify. And I think we need some details as well. So expect some verbosity. A quick answer, however, is available at the end.
c = polyfit(x,y,2) gives the coefficient vectors of the polynomial fit. You can get the fit information such as error estimate following the documentation.
Name this polynomial as P. P in Matlab is actually the function P=#(x)c(1)*x.^2+c(2)*x+c(3).
Suppose you have a single point X, then polyval(c,X) outputs the value of P(X). And if x is a vector, polyval(c,x) is a vector corresponding to [P(x(1)), P(x(2)),...].
Now that does not represent what the fit is. Just as a quick hack to see something visually, you can try plot(sort(x),polyval(c,sort(x)),'r','LineWidth',2), ie. you can first sort your data and try plotting on those x-values.
However, it is only a hack because a) your data set may be so irregularly spaced that the spline doesn't represent function or b) evaluating on the whole of your data set is unnecessary and inefficient.
The robust and 'standard' way to plot a 2D function of known analytical form in Matlab is as follows:
Define some evenly-spaced x-values over the interval you want to plot the function. For example, x=1:0.1:10. For example, x=linspace(0,1,100).
Evaluate the function on these x-values
Put the above two components into plot(). plot() can either plot the function as sampled points, or connect the points with automatic spline, which is the default.
(For step 1, quadrature is ambiguous but specific enough of a term to describe this process if you wish to communicate with a single word.)
So, instead of using the x in your original data set, you should do something like:
t=linspace(min(x),max(x),100);
plot(t,polyval(c,t),'r','LineWidth',2)

Are MATLAB's lsim outputs derivatives or the state vector?

I'm trying to do a simulation of a 2-body mass-spring-damper. I've set up a state-space model that I'm pretty confident in and set an input of a displacement and velocity at the base in just one degree of freedom. Upon getting my outputs, I expected that the output vector would just be the state vector at each time step. However, when plotting the output vector corresponding to displacement for each mass in the vertical direction (the input direction), it looked much more like a velocity (0 at the extrema of the input). The plots are shown below:
When I integrated the top 2 plots, I got the following:
Now, I obviously can just accept the outputs as they are and assume I am right in my understanding. But, I want to be sure. From the documentation page:
lsim(___) also returns the time vector t used for simulation and the
state trajectories x (for state-space models only)
I'm just hoping to find out whether or not I am correct in that the output matrix columns correspond to the history of the state derivatives before I go base an analysis on a bad assumption.
I figured it out. My B-matrix expected [derivative, state,...] but I had them in the opposite order.

I have some problems with the derivative in Matlab

In MATLAB:
Using the X and Y values below, write a MATLAB function SECOND_DERIV in MATLAB. The output of the function should be the approximate value for the second derivative of the data at x, the input variable of the function.
Use the forward difference method and interpolate to get your final answer;
X=[1,1.2,1.44,1.73,2.07,2.49,2.99,3.58,4.3,5.16,6.19,7.43,8.92,10.7,12.84,15.41,18.49];
Y=[18.89,19.25,19.83,20.71,21.96,23.6,25.56,27.52,28.67,27.2,19.38,-2.05,-50.9,-152.82,-354.73,-741.48,-1465.11];​
This is my coding:
function output = SECOND_DERIV(R)
X=[1,1.2,1.44,1.73,2.07,2.49,2.99,3.58,4.3,5.16,6.19,7.43,8.92,10.7,12.84,15.41,18.49];
Y=[18.89,19.25,19.83,20.71,21.96,23.6,25.56,27.52,28.67,27.2,19.38,-2.05,-50.9,-152.82,-354.73,-741.48,-1465.11];
%forward difference method first time.
XX=X(1:end-1)
%first derivative.
dydx=diff(Y)./diff(X)
%second derivative.
dydx2=diff(dydx)
%forward difference method second time.
XXX=XX(1:end-1)
%get the second derivative from input x.
output= interp1(XXX,dydx2,x,'linear','extrap')
end
I do not know what wrong with it.
This is the result I got from my course's web
First, there is no "the" approximate value but rather only "an" approximate value among an infinite set of approximation schemes. In that sense your excercise is ill-defined (but, to be fair, there is probably something you had in the lessons, that completes information).
Using forward differences twice is almost as bad an approximation as it can get. With each forward difference you are displacing the abscissa of the preferred (central difference) approximation by half a sample distance towards the "past".
For the first difference this can be justified by the fact that you might want to stick with the original X-samples. But in the second step you introduce a second displacement by half a sample distance. In order to keep approximation error at least reasonably low, the least you can do is to correct the displacement afterwards by one sample distance towards the "future". This doesn't bring you exactly back to central differences because of non-equidistance, but it's the minimal correction that should be done for the sake of accuracy.
Hence I would replace
XXX=XX(1:end-1)
by
XXX=XX(2:end)
But again, like so many school excercises, the problem is ill-defined and it is difficult to tell from the distance, if this is what is expected from you.

Explaining corr2 function in Matlab

Can someone explain to me the correlation function corr2 in MATLAB? I know that it is for 2D comparing similarities of objects, but in the equation I have doubts what it is A and B (probably matrices for comparison), and also Amn and Bmn.
I'm not sure how MATLAB executes this function, because I have found in several cases that the correlation is not executed for the entire image (matrix) but instead it divides the image into blocks and then compares blocks of one picture with blocks of another picture.
In MATLAB's documentation, the corr2 equation is not put as referral point to the way the equation itself is calculated, like in other functions in MATLAB's documentation, such as referring to what book it is taken from and where it is explained.
The correlation coefficient is a number representing the similarity between 2 images in relation with their respective pixel intensity.
As you pointed out this function is used to calculate this coefficient:
Here A and B are the images you are comparing, whereas the subscript indices m and n refer to the pixel location in the image. Basically what Matab does is to compute, for every pixel location in both images, the difference between the intensity value at that pixel and the mean intensity of the whole image, denoted as a letter with a straightline over it.
As Kostya pointed out, typing edit corr2 in the command window will show you the code used by Matlab to compute the correlation coefficient. The formula is basically this:
a = a - mean2(a);
b = b - mean2(b);
r = sum(sum(a.*b))/sqrt(sum(sum(a.*a))*sum(sum(b.*b)));
where:
a is the input image and b is the image you wish to compare to a.
If we break down the formula, we see that a - mean2(a) and b-mean2(b) are the elements in the numerator of the above equation. mean2(a) is equivalent to mean(mean(a)) or mean(a(:)), that is the mean intensity of the whole image. This is only calculated once.
The 3rd line of code calculates the coefficient. Here sum(sum(a.*b)) calculates the double-sum present in the formula element-wise, that is considering each pixel location separately. Be aware that using sum(a) calculates the sum in every column individually, hence in order to get a single value you need to apply sum twice.
That's pretty much the same happening in the denominator, however calculations are performed on a-mean2(a)^2 and b-mean2(b)^2. You can see this a some kind of normalization process in which you consider the pixel intensity difference among each individual image.
As for your last comment, you can break down an image into small blocks and calculate the correlation coefficient on them; that might save some time for very large images but since everything is vectorized the calculation is quite fast. It might be useful in distributed processing I guess. Of course the correlation coefficient between 2 blocks of images is not necessarily identical to that of the whole image.
For the sake of curiosity you can look at this paper which highlights some caveats in using the correlation coefficient for image comparison.
Hope that makes things a bit clearer!

fundamental matrix keeps changing in matlab but same using open cv.what might be the reason?

I have calculated fundamental matrix using the function shown below
[fMatrix, epipolarInliers, status] = estimateFundamentalMatrix(...
matchedPoints1, matchedPoints2, 'Method', 'RANSAC', ...
'NumTrials', 10000, 'DistanceThreshold', 0.1, 'Confidence', 99.99);
but here in this case fundamental matrix keeps varying each time i run the program.
but when i use the code shown below in open cv i get the same fundamental matrix everytime i run the program.code is shown below
cv::Mat fundamental=cv::findFundamentalMat(cv::Mat(selPointsLeft),cv::Mat(selPointsRight),CV_FM_RANSAC);
in both the cases i used surf features to extract the match features.Matchpoints1=selpointsleft and matchpoints2=selpointsright.
What might the reason for this?
RANSAC is an abbreviation for "RANdom SAmple Consensus". That said, we must expect the output matrix to change as the samples are randomly picked.
In OpenCV, the values are picked from a uniformly distributed list of random values. Thus we get the same values every time we run the code.
In Matlab, it that seems to pick a completely random value and hence the problem. You will have to check whether there is a way to random-seed the picking of random values, which I am quiet unsure of.