MATLAB Answers

Question about functions in MATLAB

13 views (last 30 days)
Girish Kolli
Girish Kolli on 4 Jun 2018
Commented: Star Strider on 4 Jun 2018
What is the difference between this code
function result = square(n)
result = n*n;
and this code
number = 4;
numberSquared= square(number);
Like I'm confused about the first code specifically. Are both the codes doing the same thing or is there a difference?


Sign in to comment.

Answers (2)

Star Strider
Star Strider on 4 Jun 2018
The first code is a function, and the second code is a script that calls the function.
Because one is a function and the other is a script, they are different.


Show 1 older comment
Walter Roberson
Walter Roberson on 4 Jun 2018
Nothing is automatically returned from a function. Only variables declared on the left of the = in the function definition will have their values transferred out to the calling code.

Sign in to comment.

Varun Garg
Varun Garg on 4 Jun 2018
Hi Girish
As it has already been mentioned that the first code is function and the other one is a script.
I suppose you get the point but are wondering about the basic difference between them. To make things clearer, suppose we have a variable x in our work space say
x=10 (typing this in the console).
Suppose your function is in the file sq1.m. Code is as follows :
function sq1(x)
If you want to access it from command line, you have to type
because functions have their own local space so you need to explicitly pass argument.
On the other hand, consider your script file sq2.m with same workspace. Code is as follows:
If you want to access it from command line, you just need to type
So in simple words:
Each statement in a script is equivalent to typing them out at the command window of MATLAB. You're just storing them before-hand in a file!
A function, on the other hand, takes in arguments and is a "new" workspace, separate from the main workspace.

  1 Comment

Girish Kolli
Girish Kolli on 4 Jun 2018
Got it! Thank you so much!

Sign in to comment.

Sign in to answer this question.




Translated by