Question about functions in MATLAB

조회 수: 4 (최근 30일)
Girish Kolli
Girish Kolli 2018년 6월 4일
답변: shaik faraz 2022년 4월 8일
What is the difference between this code
function result = square(n)
result = n*n;
end
and this code
number = 4;
numberSquared= square(number);
disp(numberSquared);
Like I'm confused about the first code specifically. Are both the codes doing the same thing or is there a difference?

채택된 답변

Varun Garg
Varun Garg 2018년 6월 4일
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)
disp(x*x);
end
If you want to access it from command line, you have to type
sq1(x)
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:
disp(x*x);
If you want to access it from command line, you just need to type
sq2
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개)

shaik faraz
shaik faraz 2022년 4월 8일
upper one is a function
lower one is a script
script only gets you result if u run that particular script
but function can be called from other scripts

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by