# Matlab Equation

Discussion in 'Programmer's Corner' started by Cerkit, Jan 13, 2010.

1. ### Cerkit Thread Starter Senior Member

Jan 4, 2009
286
3
Hi. How is it possible to write an equation for example f=X^2 so that anywhere in my code I can get the value of f for a given X by typing

F(X)

for some X value?

Thanks

2. ### steveb Senior Member

Jul 3, 2008
2,432
469
Simply create a function and put it in an m-file with the same name as your function. For example, for your squaring function chose a name like "Xsquared" for your function and store the function in a file called Xsquared.m. The function code in this m-file would look as follows in this case.

Code ( (Unknown Language)):
1.
2. [FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff]function[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][FONT=Courier New][SIZE=2][FONT=Courier New][SIZE=2] [output_value] = Xsquared(x)[/SIZE][/FONT]
3. [SIZE=2][FONT=Courier New]output_value = x^2;[/FONT][/SIZE]
4. [/SIZE][/FONT][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff]end[/COLOR][/SIZE][/FONT]
5. [/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT]
To call the function, simply do the following Y=Xsquared(2) and Y will be set equal to 4 (or the square of whatever value you plug in). Make sure the function file in in your working directory, or keep it in a directory that Matlab can access for functions.

Last edited: Jan 13, 2010