two questions. (ascending order, ASCII)

1 次查看(过去 30 天)
Lim Miso
Lim Miso 2015-10-19
#1
function hw(N)
A=zeros(1,N);
for i=1:N
A(i)=input('Enter a number: ');
end
i have this code.
From now on, i have to make these numbers in ascending order.
But i can not use SORT function.
#2
I got the result screen.
I have to make a code for this result.
[65]A [66]B [67]C [68]D [69]E
[66]B [68]D [70]F [72]H [74]J
[67]C [70]F [73]I [76]L [79]O
[68]D [72]H [76]L [80]P [84]T
[69]E [74]J [79]O [84]T [89]Y
please help.
  3 个评论
Lim Miso
Lim Miso 2015-10-20
I tried to use Bubble sorr, but i got another problem. I had never learned SWAP command. So is there any command that i can use instead of SWAP code in the bubble sort.?
Image Analyst
Image Analyst 2015-10-20
The swap command can be done with the "deal()" function:
a=10
b=20
[b, a] = deal(a, b)
In the command window you'll see:
a =
10
b =
20
b =
10
a =
20
Take special note of the order that the variables are in.

请先登录,再进行评论。

回答(2 个)

TastyPastry
TastyPastry 2015-10-19
For #1, you can either sort as the user inputs numbers or sort at the end. Personally, I'd just sort it at the end for simplicity's sake. Since you can't use sort(), you'll have to write your own sorting function. Code for various sorting methods is readily available online. You could just write a bubble sort because it's one of the easiest to understand. It's slow, but I doubt you'll be working with massive vectors for this code. There are ways of using Matlab's other built-in functions to return sorted lists (unique() can, but you have to twiddle around with it a bit), but for the sake of homework, it's probably better to write your own sort.
For #2, I'd create 5 vectors of ASCII values using the : operator and concatenating them into an array. Then, use a nested for loop to individually format each number into a cell array of strings. For example, for the first value 65,
myCell{index} = ['[' num2str(myArr(index)) ']' char(myArr(index))];

Image Analyst
Image Analyst 2015-10-19
For #2, here's a huge hint:
for row = 1 : 5
for col = 1 : 5
fprintf('[%d]%c ', col+63+row, col+63+row);
end
fprintf('\n');
end
Making a slight modification to it will solve your homework. I'm sure a smart engineer like you can figure out what that might be.

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by