Calling function from another .m file

16 views (last 30 days)
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);

Answers (1)

Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh on 12 Sep 2021
type this in your script:
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 ; .
  2 Comments
Joe Ainsworth
Joe Ainsworth on 12 Sep 2021
@Abolfazl Chaman Motlagh, this didnt work for whatever reason. what do you mean by put the variable in argument of function as in A = stringorder(f)?
its giving men an error on line 4
[M,N]=size(A)
Abolfazl Chaman Motlagh
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.)

Sign in to comment.

Categories

Find more on Environment and Settings in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!