I've done the tutorials and searched the forums and I cannot find an answer to my question. I want to define a series of functions that I can call on using the function and its associated values. Like this:
F(x,y,z)=x*y*z -this is a dumbed down version of what I need F(1,2,3)= 6 -this is the result I'm hoping to get so that I can use the function for various scenarios.
That way I can define a particular case z=f(1,2,3) z=6

 Accepted Answer

I would create them as Anonymous Functions (link).
Example
F = @(x,y,z) x*y*z;
q = F(1,2,3)
q =
6

3 Comments

Kevin Edlebeck
Kevin Edlebeck on 4 Feb 2018
Edited: Kevin Edlebeck on 4 Feb 2018
Thats what I've been trying, here is what I have:
>>function [Ec]=IsoStrain(x)
>>Ec=Er*Vr+Em*Vm
>>end
>>values=[1 2 3 4];
>>Ec=IsoStrain(values)
and the corresponding error.
>> Test_Function Error: File: Test_Function.m Line: 5 Column: 1 Function definitions in a script must appear at the end of the file. Move all statements after the "IsoStrain" function definition to before the first local function definition.
ok, so I did it the way you suggested and it work, would you mind giving me a quick FYI about how this works. Just lame terms, I'm not incredible program savy. Does this work with an array?
I cannot go into detail about how MATLAB handles functions work because I have not inquired into it. (I once knew how FORTRAN created the stack interfaces and such, since I had to write assembly language functions and had to know how to make them compatible with the FORTRAN compiler.)
When you create a function, you give it a list of inputs (arguments) to use within the function to calculate the result you want. See Function Basics (link) for details. They are designed to work essentially as algebraic functions work.
Note that anonymous functions will use variables from your user workspace unless you declare those variables with the same names as your workspace variables to be function arguments. Then it uses the variables passed to it as arguments instead.
Functions work with arrays if you write them to do so. See the documentation on Array vs. Matrix Operations (link) and Vectorization (link) for details.
I am not avoiding answering your questions about functions. The MATLAB documentation discusses them much more clearly and efficiently than I can, so I direct you to it.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!