フィルターのクリア

Matlab Sort Command Output

3 ビュー (過去 30 日間)
Veysel Ahmet Özdemir
Veysel Ahmet Özdemir 2020 年 5 月 14 日
I have an equation and the user enters certain numbers into this equation, then it gets x1 x2 x3 numbers but wants them in result with sort, I use the "sort" command for this, but "sort" writes the value of x1. I want the result to be in x1 x2 x3. For example, equation gives me
x1=3 x2=1 x3=2 a=[x1 x2 x3] sort (a) = 1 2 3
I want it to be x2 x3 x1. How can I do that?

回答 (2 件)

Tommy
Tommy 2020 年 5 月 14 日
How about this?
x1=3;
x2=1;
x3=2;
a=[x1 x2 x3];
varNames = {'x1','x2','x3'};
[~, idx] = sort(a);
fprintf('Output:\n%s\n', strip(sprintf('%s ', varNames{idx})))
Prints:
Output:
x2 x3 x1
Or if you don't want to have to type the variable names, I guess you could do this?
fprintf(mySort(x1, x2, x3));
function s = mySort(varargin)
[~, idx] = sort(cell2mat(varargin));
s = cell(numel(idx),1);
for i = 1:numel(idx)
s{i} = inputname(idx(i));
end
s = sprintf('Output:\n%s\n', strip(sprintf('%s ', s{:})));
end
Which prints the same thing.
  1 件のコメント
Veysel Ahmet Özdemir
Veysel Ahmet Özdemir 2020 年 5 月 14 日
It worked very well, thank you so much. Can you explain the logic, it was just copy and paste for me, I want to understand the logic of the commands. In addition, I will do this more than once for various numbers, there is a code that I can show these outputs as a table, I did some research but I couldn't find it :(

サインインしてコメントする。


Stephen23
Stephen23 2020 年 5 月 14 日
編集済み: Stephen23 2020 年 5 月 14 日
Using separate variables makes this rather complex.
It would be much simpler if you stored the data in arrays, e.g. in one table:
>> names = {'x1';'x2';'x3'};
>> values = [3;1;2];
>> T = table(names,values)
T =
names values
_____ ______
'x1' 3
'x2' 1
'x3' 2
>> T = sortrows(T,'values') % this is all you need
T =
names values
_____ ______
'x2' 1
'x3' 2
'x1' 3
Better data design -> simpler, neater, more efficient code.
  1 件のコメント
Veysel Ahmet Özdemir
Veysel Ahmet Özdemir 2020 年 5 月 14 日
Thank you so much but i need 2 tables. The first table should only include "x"s. For exp.:
1: x1 x2 x3
2: x2 x3 x1
....
The second table should only include values. For exp.:
1: 1 2 3
2: 2 3 5

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by