Differences between script and function file

9 views (last 30 days)
Esther
Esther on 18 Sep 2012
Does script file and function file relate to one another when comes to coding? or it's two different file? I saw alot of tutorial but i still do not understand.

Answers (2)

Jürgen
Jürgen on 18 Sep 2012
Edited: Jürgen on 18 Sep 2012
Hi,
the coding between script file and function is the same, only the header is different
let's say I make in a script I want to calculate the mean of of some numbers
A= [ 1 2 3 4 5 6]
mean1= (1+2/2) mean2=(3+4/2) mean3=(5+6)/2
instead of writing and copying nearly the same code use a function that you create:( this just a simple example there is an inbuilt function for it of course) you start the function always with the header function .....
function [Mean]= CalcMean(Input)
Mean=( sum(Input)/size(Input,2))
rJ
  1 Comment
Esther
Esther on 18 Sep 2012
thanks for replying. so is it a must to have both file? or i can just use 1 file type for image processing?

Sign in to comment.


Isktaine
Isktaine on 18 Sep 2012
Edited: Isktaine on 18 Sep 2012
A script file will run one line after another, and all the information is available to your workspace in MATLAB. For example if you run the script
%some saved script
A=46;
B=49;
C=A-B;
You will now have the variables A,B and C in your workspace. All you can do is run the script file and replay those 3 lines over and over. If you wrote a function
function C=pointless_task(D,E)
C=D-E;
end
and click the run button then nothing will happen if D and E have not been defined. However if you save the function then go to your MATLAB command line and write C=pointless_task(46,49) you will get a value for C in your workspace. It will have put your D and E into the function and not saved them. With the function you can effectively run the same script over and over with different values. You could write P=pointless_task(13,15) and get an instant answer rather than writing a whole new script and running it.
So you can have one or the other. Hope this makes sense.

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!