a =
Sorting array of sym
显示 更早的评论
I get wrong answers in this case. Am I doing anything wrong ?
>> a = sym.empty();
>> a = [a,0,pi,pi/2,-pi/2,pi/4]
a =
[0, pi, pi/2, -pi/2, pi/4]
>> sort(a)
ans =
[0, pi, -pi/2, pi/2, pi/4]
4 个评论
Torsten
2024-7-15
Symbolic arrays are sorted according to their lexicographic order, not their numerical order.
Paul
2024-7-15
Any idea what lexicographic order means in the Symbolic Toolbox? I mean, what are the "alphabet" and "word" definitions that lexicographically define all things the toobox supports, like sybolic constants, variables, expressions, etc. The doc page under the "Input Arguments" section does define some rules for specific cases, but in the most general case it just says: "Therefore, sort uses internal sorting rules to optimize its performance."
Pi = sym(pi);
a = [-Pi/4 -Pi/3 -Pi/2 -Pi -Pi*3/4 -Pi*2/3 Pi/4 Pi/3 Pi/2 Pi Pi*3/4 Pi*2/3 -Pi*1/5 -Pi*2/5 -Pi*3/5 -Pi*4/5 Pi*1/5 Pi*2/5 Pi*3/5 Pi*4/5]
sort(a)
a = a(randperm(numel(a)))
sort(a)
So the sorting results are stable, but they are not obvious.
Tanmaya
2024-7-18
回答(1 个)
Hi Tanmaya
To sort the symbolic array numerically, you can convert the symbolic expressions to their numerical equivalents before sorting. Here's how you can do it:
- Convert the symbolic expressions to numerical values.
- Sort the numerical values.
- Recreate the sorted symbolic array using the indices from the sorted numerical values.
Please refer to the following code snippet to implement the same:
a = sym.empty();
a = [a, 0, pi, pi/2, -pi/2, pi/4];
a = sym(a); % Ensure the array is symbolic
% Convert to numerical values
num_a = double(a);
% Sort the numerical values and get the sorting indices
[sorted_num_a, sort_idx] = sort(num_a);
% Recreate the sorted symbolic array using the indices
sorted_a = a(sort_idx);
disp(sorted_a);
Hope this helps!
2 个评论
This is pretty much all you can do, to convert the elements to actual numbers in some form. But there is no value in creating a as a sym.empty first.
a = sym([0, pi, pi/2, -pi/2, pi/4]);
a = sym(a)
You don't need ot go all the way to doubles though. vpa would seem more accurate, and still works.
[~,idx] = sort(vpa(a));
a = a(idx)
Tanmaya
2024-7-18
类别
在 帮助中心 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!