How can I determine if the absolute value of a coefficient of x in each element of a matrix was less than 0.01 consider it zero?
3 次查看(过去 30 天)
显示 更早的评论
For example I have the below matrix 2*2
a=[ e-8(X^2)+12X-e-6(X)+14, -10(X^2)+0.001X-e-6(X^3); X, 4]
I want to write the code so that it give me:
a=[ 12X+14, -10(X^2); X 4]
3 个评论
Walter Roberson
2023-7-6
could you confirm that this is a question symbolic expressions? If so I posted code for this about 4 years ago but it might be hard to locate. Might be easier to rewrite.
回答(2 个)
Image Analyst
2023-7-6
Then just write it as a=[ 12X+14, -10(X^2); X 4] with whatever value you have for X.
Why can't you? Do you not know what the coefficients are? Like they're not hard coded in like you have but they're somehow contained in another matrix b so that
b = [ e-8, 12, -e-6,+14, -10,+0.001, -e-6; 1, 4]
a = [ b(1) * (X^2)+ b(2) * X + b(3) * X+b(4), b(5) * (X^2), b(6) * X + b(7) * (X^3); ...
b(8) * X, b(10)]
so you can just use that a but zero out elements of b before using b, like
b = [ e-8, 12, -e-6,+14, -10,+0.001, -e-6; 1, 4] % Original list of coefficients.
b(b < 0.01) = 0; % Get rid of small coefficients.
X = 42; % Whatever.....
% Now compute a
a = [ b(1) * (X^2)+ b(2) * X + b(3) * X+b(4), b(5) * (X^2), b(6) * X + b(7) * (X^3); ...
b(8) * X, b(10)]
2 个评论
Sam Chak
2023-7-6
Can you introduce the if-else statement such that you have more control freedom to define the rules when a particular input is given?
Walter Roberson
2023-7-6
sympref('floating', false);
tolerance = 0.01;
syms X
a=[ 1e-8*(X^2)+12*X-1e-6*(X)+14, -10*(X^2)+0.001*X-1e-6*(X^3); X, 4]
a_new = mapSymType(a, 'real', @(value) piecewise(value < -tolerance | value > tolerance, value, 0))
Note that this does not give you exactly what you were hoping for. Your notation was unclear so I had to guess that 12X-e-6(X) represents 12*X-1e-6*(X) . But MATLAB would never hold those two coefficients of X separate: it would always combine them, and the only question is whether they are going to get combined as the rational 12 - 1/10^6 or as floating point 12.0 - 0.000001 .
The situation would be different if one of the coefficients had an additional variable; for example 12*X-1e-6*rho*(X) would not automatically combine.
If somehow you had an input of 12*X-1e-6*(X) and you wanted to do the coefficient reduction before combining the coefficients, then you would have to wrap each entry in a function or else you would need to do text manipulation on text expressions before converting the text to symbolic.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!