1
$\begingroup$

I am using least squares approximation to fit the data in Y. However when I attempt to plot the the curve g[x] using the results from LinearSolve, there is no plot output.

X = Range[0, 0.9, 0.1];
M = Length[X];
Y = {0, 0.11723, 0.16527, 0.28996, 0.355861, 0.446146, 0.476244, 0.443929, 0.424399, 0.386496};
A = Table[X[i]^j, {i, 1, M}, {j, 1, 3, 2}];
K = LinearSolve[Transpose[A].A, Transpose[A].Y];
g[x_] := K[[1]]*x + K[[2]]*x^3;
Plot[{g[x], {x, 0, 0.9}]
$\endgroup$
  • 1
    $\begingroup$ I think your A = Table[X[i]^j, {i, 1, M}, {j, 1, 3, 2}]; line should be A = Table[X[[i]]^j, {i, 1, M}, {j, 1, 3, 2}]; (note the extra brackets around i). Also make sure to remove the extra { in Plot before g[x]. One trick I use to find issues like this is by examining each variable I've set to see if it's what I think it should be. Running K by itself in your code results in a gigantic output. I assumed that wasn't correct, so worked backwards and asked for what A was. It was also a really big output, that I don't think was expected. X, M, and Y, were all what I expected. $\endgroup$ – MassDefect May 4 at 6:56
  • 1
    $\begingroup$ Also, if you're new to Mathematica, try to avoid using capital letters for variables unless you are familiar with which ones are reserved. C, D, E, I, K, N, and O are all used by the system and can lead to unexpected problems. $\endgroup$ – MassDefect May 4 at 6:59
  • $\begingroup$ @MassDefect Thank you, will do, I'm still getting used to the syntax $\endgroup$ – photon May 5 at 19:55
1
$\begingroup$

You really should always look at result of each step you did to find the problem, and not at the last step. If you did, you'd seen the problem. You used [] instead of [[ ]] when calculating A

X = Range[0, 0.9, 0.1];
M = Length[X];
Y = {0, 0.11723, 0.16527, 0.28996, 0.355861, 0.446146, 0.476244, 
   0.443929, 0.424399, 0.386496};
A = Table[X[[i]]^j, {i, 1, M}, {j, 1, 3, 2}];
g[x_] := K[[1]]*x + K[[2]]*x^3;
Plot[g[x], {x, 0, 0.9}]

Mathematica graphics

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.