Calling function from another .m file

62 次查看(过去 30 天)
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);

回答(1 个)

Abolfazl Chaman Motlagh
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 个评论
Joe Ainsworth
Joe Ainsworth 2021-9-12
@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
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.)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by