Borrar filtros
Borrar filtros

Sorting array of sym

49 visualizaciones (últimos 30 días)
Tanmaya
Tanmaya el 15 de Jul. de 2024 a las 18:21
Comentada: Tanmaya el 18 de Jul. de 2024 a las 16:51
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 comentarios
Walter Roberson
Walter Roberson el 15 de Jul. de 2024 a las 19:42
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]
a = 
sort(a)
ans = 
a = a(randperm(numel(a)))
a = 
sort(a)
ans = 
So the sorting results are stable, but they are not obvious.
Tanmaya
Tanmaya el 18 de Jul. de 2024 a las 16:51
Thanks

Iniciar sesión para comentar.

Respuestas (1)

Milan Bansal
Milan Bansal el 15 de Jul. de 2024 a las 18:45
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:
  1. Convert the symbolic expressions to numerical values.
  2. Sort the numerical values.
  3. 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 comentarios
John D'Errico
John D'Errico el 15 de Jul. de 2024 a las 19:59
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)
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)
a = 
Tanmaya
Tanmaya el 18 de Jul. de 2024 a las 16:50
Thanks

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by