TransWikia.com

How can I rewrite this code to work for every $n$

Mathematica Asked by Ali AlCapone on December 11, 2020

I wanted to write this code in such a way that I run the whole thing for each $n$, and not write a1 a2 a3 or eq1 eq2 eq3 every time.

Clear[y, x, M, V, th, EI, PE]
y = a4*x^4 + a3*x^3 + a2*x^2;
th = D[y, x];
M = EI*D[y, {x, 2}];
V = EI*D[y, {x, 3}];
PE = EI/2*Integrate[D[y, {x, 2}]^2, {x, 0, L}] + P*(y /. x -> L);
Eq2 = D[PE, a2];
Eq1 = D[PE, a3];
Eq3 = D[PE, a4]
Sol = Solve[{Eq1 == 0, Eq2 == 0, Eq3 == 0}, {a3, a2, a4}];
y = y /. Sol[[1]];
th /. Sol[[1]];
FullSimplify[M /. Sol[[1]]]
FullSimplify[V /. Sol[[1]]]

Here’s my attempt but it doesn’t work:

Clear[a, y, x, M, V, th, EI, PE]
n = 4
y = Sum[{y^i}*a[i], {i, 0, n}]
th = D[y, x];
M = EI*D[y, {x, 2}];
V = EI*D[y, {x, 3}];
PE = EI/2*Integrate[D[y, {x, 2}]^2, {x, 0, L}] + P*(y /. x -> L)
Eq = Table [{D[PE, a[i]]}, {i, 2, n}]
Sol = Solve[{Eq[i] == 0}, {a[i]}];
y = y /. Sol[[1]];
th /. Sol[[1]];
FullSimplify[M /. Sol[[1]]]
FullSimplify[V /. Sol[[1]]]

One Answer

Be careful not to define things recursively like y. Use Array[a, n] to produce the list {a[1],a[2],a[3],a[4]}. You also do not need some of the lists {...} like in your Table and Solve, and you can use ConstantArray to make your zero vector for the equations:

Remove["Global`*"]
n = 4;
y = Sum[x^i*a[i], {i, 0, n}]
th = D[y, x];
M = EI*D[y, {x, 2}];
V = EI*D[y, {x, 3}];
PE = EI/2*Integrate[D[y, {x, 2}]^2, {x, 0, L}] + P*(y /. x -> L)
Eq = Table[D[PE, a[i]], {i, 2, n}]
sol = Solve[Eq == ConstantArray[0, n - 1], Array[a, n]]
y /. sol
th /. sol
Eq /. sol
FullSimplify[M /. sol[[1]]]
FullSimplify[V /. sol[[1]]]

(* {{a[2] -> -((L P)/(2 EI)), a[3] -> P/(6 EI), a[4] -> 0}} *)

Correct answer by flinty on December 11, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP