Calling function from another .m file

3 views (last 30 days)
Joe Ainsworth on 12 Sep 2021
Trying to call a function from another file called stringorder.m but getting an error, can someone please explain why.
thank you!
This is the fucntion file
function f = ["Benn" ; "Dan" ; "Lebron" ; "Jim" ; "Rose"];
here is my script
function A = stringorder ;
[M,N]=size(A);
for i = 1:M-1
for j = 1:M-1
curr = A(j);
next = A(j+1);
if upper(curr) > upper(next)
A(j) = next;
A(j+1) = curr;
end
end
end
disp(A);

Abolfazl Chaman Motlagh on 12 Sep 2021
function A = stringorder(A)
[M,N]=size(A);
for i = 1:M-1
for j = 1:M-1
curr = A(j);
next = A(j+1);
if upper(curr) > upper(next)
A(j) = next;
A(j+1) = curr;
end
end
end
disp(A);
end
and save it in stringorder.m .
then you have to put the variable in argument of your function:
f = ["Benn" ; "Dan" ; "Lebron" ; "Jim" ; "Rose"];
F_output = stringorder(f)
also you don't have to use disp(A) at end. the output of function will be printed if you don't use ; .
Abolfazl Chaman Motlagh on 12 Sep 2021
how is this ( [M,N]=size(A) ) in line 4 ? it is in line 2!
you should open a new script. copy the function part of code. save it with same name of function.( here is stringorder) (so the file should be stringorder.m)
then whenever you want to use function, for example in command window of matlab, you have to write name of function and then open parantheses, put your variable and close the parantheses.
% write this on command window :
A = ["Joe" ; "David" ; "Peter"]; % for example
A = stringorder(A)
so you should write second part of code in command window. (or another file which is runnig in same folder with function file.)

R2021a

Community Treasure Hunt

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

Start Hunting!