How to use output numbers as a vector.
Ältere Kommentare anzeigen
The code I'm working on does what it's supposed to, however, I technically want it to output the values as a vector b instead of a message with the numbers.
The goal of this function is to input a vector and have the program sort them from smallest to largest, but without using the sort function.
The code I'm using is
clear variable
clc
a=input('Please input a vector of integers');
c=length(a);
for d = unique(a(:))
b=(sprintf('%d',d));
end
clc
sprintf('b= ')
disp(b)
right now the answer I'm getting is:
ans =
'b= '
2469
this is based upon the vector [9 4 6 2]
What I want to see output is:
b =
2 4 6 9
this output was copied from my teachers p code and is technically what my output should look like.
Yes this is homework.
3 Kommentare
You're overwriting b every iteration. You also don't need the loop, as sprintf can handle array inputs just fine.
Also, this assignment (or your interpretation) seems a bit strange. Why would you be required to convert the numbers to characters as well? The output looks as if this is the source:
a=[9 4 6 2];
b=sort(a)
Also, you're not using c, and you should check if the implicit call to sort inside of unique is allowed.
Brendan Clark
am 6 Apr. 2021
Brendan Clark
am 6 Apr. 2021
Akzeptierte Antwort
Weitere Antworten (1)
Mathieu NOE
am 6 Apr. 2021
hello
see bleow :
clear variable
clc
a=input('Please input a vector of integers : ');
c=length(a);
for d = unique(a(:))
b=(sprintf('%d ',d)); % add a blank after "%d"
end
clc
sprintf('b = %s', b)
1 Kommentar
Rik
am 6 Apr. 2021
This code only works as intended because d is a column vector, all elements of a are integers, and there are no duplicate values.
Kategorien
Mehr zu Multidimensional Arrays finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!