Sort data Matlab program errors.

2 views (last 30 days)
Oliver
Oliver on 19 Dec 2011
Dear all,
I'm a newbie to Matlab programming and need some help. I wrote a program to sort the input data in ascending order. However, the functions did not work properly. Can you please shed some light? Thanks heaps.
Oliver.
nvals =input('Enter number of values in the data set: ');
array = zeros(nvals,1);
sorted = zeros(nvals,1);
for ii = 1:nvals
string = ['Enter value ' int2str(ii) ': '];
array(ii) = input(string);
end
sorted = ssort(array);
fprintf('\nSorted data: \n');
for ii = 1:nvals
fprintf(' %8.4f\n', sorted(ii));
end
function out = ssort(a)
for i=1:nvals
if array(i)>array(i+1)
sorted(i) = array(i+1);
sorted(i+1) = array(i);
array(i+1) = array(i);
else
sorted(i) = array(i);
end
end
out = a;
*Errors are as follows: ??? Undefined function or method 'sorted' for input arguments of type 'double'.
Error in ==> test_ssort at 11 fprintf(' %8.4f\n', sorted(ii));
??? Error: File: test_ssort.m Line: 14 Column: 1 Function definitions are not permitted in this context.
??? Error: File: test_ssort.m Line: 17 Column: 1 Function definitions are not permitted in this context.
??? Error: File: test_ssort.m Line: 17 Column: 1 Function definitions are not permitted in this context.
??? Error: File: test_ssort.m Line: 18 Column: 1 Function definitions are not permitted in this context.
??? Error: File: test_ssort.m Line: 18 Column: 1 Function definitions are not permitted in this context.*

Answers (1)

Wayne King
Wayne King on 19 Dec 2011
Looks like you are trying to define a function inside of a script, test_ssort.
You should save your ssort.m file into a folder that is on the MATLAB search path. Then you can call that function in your script. Remove the declaration of the function from the script.
However, I immediately see you have some problems with your function, ssort.m. You input, a, but then inside the function you work on array. That is not going to work, you should change the function definition to use array. Further, the last line
out = a;
is not going to work. There is nothing in the function assigned to out.

Categories

Find more on File Operations in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!