how to cover math expression to symbolic expr.?

1 visualizzazione (ultimi 30 giorni)
Anas Zh
Anas Zh il 22 Lug 2022
Commentato: Steven Lord il 22 Lug 2022
AA,
I have this code,
syms V B G H
V=[G^1 G^2 B^3; B^4 B^5 G^6; B^7 B^8 B^9];
for k=1:9
BB(k)=B^k;
VV(k)=k;
end
VB=subs(V,[BB],[VV])
V =
[ G, G^2, B^3]
[B^4, B^5, G^6]
[B^7, B^8, B^9]
BB =
[B, B^2, B^3, B^4, B^5, B^6, B^7, B^8, B^9]
VV =
1 2 3 4 5 6 7 8 9
VB = % The answer
[G, G^2, 1]
[1, 1, G^6]
[1, 1, 1]
As you can see the answer, the code deal with B^k as a symbolic var. B and the power as math expr.
So the answer looked like this. I want the code to deal with for example B^4 as one symbolic var. to prevent it to be mathmaticlly used. So, the needed answer is
VB = % The needed answer
[G, G^2, 3]
[4, 5, G^6]
[7, 8, 9]

Risposte (1)

Walter Roberson
Walter Roberson il 22 Lug 2022
This was a bit tricky -- and the code as-is will not handle the case of B by itself (it would leave the B there unchanged.)
This code uses several "tricks". There is no way that I know of to directly code a test for a specific variable to a power, so you have to look for power in general, and then you have to test whether the base is identical to the variable, telling it that unprovable should be treated as not identical. Then because isAlways returns logical you have to compare the logical result to symtrue in order to convert the logical to symbolic logical that piecewise() is willing to live with.
This is far from straight-forward, and MATLAB really should improve the situation.
syms V B G H
V=[G^1 G^2 B^3; B^4 B^5 G^6; B^7 B^8 B^9];
for k=1:9
BB(k) = B^k;
VV(k) = sym(k);
end
VB = simplify(mapSymType(V, "power", @(P) piecewise(isAlways(children(P,1)==B,'unknown', 'false')==symtrue, VV(children(P,2)), P)))
VB = 
  1 Commento
Steven Lord
Steven Lord il 22 Lug 2022
I'd go for a slightly different approach using logs. It does require the addition of an assumption that B is positive.
syms V B G H
V=[G^1 G^2 B^3; B^4 B^5 G^6; B^7 B^8 B^9];
for k=1:9
BB(k) = B^k;
VV(k) = sym(k);
end
assume(B, 'positive')
powersOfB = log(V)./log(B)
powersOfB = 
If we were to simplify powersOfB, the assumption that B is positive lets element (1, 3) simplify to 3 (as an example.)
simplify(powersOfB)
ans = 
Symbolic Math Toolbox can tell that 3 is always going to be equal to round(3). But it can't tell whether element (1, 1) which is (before and after simplification) will always be equal to round(). So we can use isAlways, telling Symbolic Math Toolbox to just return false (without a warning) if it can't tell.
isPurelyPowerOfB = isAlways(powersOfB == round(powersOfB), Unknown='false')
isPurelyPowerOfB = 3×3 logical array
0 0 1 1 1 0 1 1 1
V(isPurelyPowerOfB) = simplify(powersOfB(isPurelyPowerOfB))
V = 

Accedi per commentare.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by