two questions. (ascending order, ASCII)

3 views (last 30 days)
Lim Miso
Lim Miso on 19 Oct 2015
Commented: Image Analyst on 20 Oct 2015
#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 Comments
Lim Miso
Lim Miso on 20 Oct 2015
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 on 20 Oct 2015
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.

Sign in to comment.

Answers (2)

TastyPastry
TastyPastry on 19 Oct 2015
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 on 19 Oct 2015
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.

Community Treasure Hunt

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

Start Hunting!