Defining and calling functions in MATLAB

Given: Recall that Fahrenheit and Celsius are related by the following equation:
Find: Create a function called tempC2F that will accept an input argument of a single temperature in degrees Celsius and return the equivalent temperature in degrees Fahrenheit. I should be able to call your function using the following function call: TF=tempC2F(TC)
My Solution: This is what I have, but I am not getting the desired result, I'm not sure how to call the function to run...
function
Invalid expression. Check for missing or extra characters.
tempC2F=(1.8*tC)+32
end
% You can test your function using the following function call. Recall that 212F is the boiling point of water at sea level.
% This corresponds to 100C. If you click "Run", the following code will call your function. You should get an output of tF=212.
% Remember that we are "Calling" the function below. As such, the variable names do not have to match the variables used in the function above.
% Those variables are specific to the function itself.
tC = 100;
tF = tempC2F(tC)

 Accepted Answer

Voss
Voss on 27 Feb 2024
Refer to the following documentation page for a description and examples of how to define and call a function:

5 Comments

I have read the documentation, help menu in MATLAB, and looked up some videos on Youtube. I just can't fathom it with their simple vague examples for this particular problem.
function ave = calculateAverage(x)
ave = sum(x(:))/numel(x);
end
Call the function from the command line.
z = 1:99;
ave = calculateAverage(z)
ave =
50
This example isn't intuitive to me...
The example function, called calculateAverage, takes a numeric input and returns the average of its elements. In the definition of the function, the input is called x and the output is called ave.
function ave = calculateAverage(x) % this line defines the function name (calculateAverage) and its input (x) and output (ave)
ave = sum(x(:))/numel(x); % the stuff inside the function (between "function" and "end") does the calculation
end % this line says the function definition is done
Your task is to write a function called tempC2F that takes a numeric input, temperature in degrees Celsius, converts it to degrees Fahrenheit, and returns the converted value. The conversion calculation you have written is OK. So all that's left to do is to name your function and define its input and output. The task tells you what the name of the function must be (tempC2F), so really you just need to pick names for the input and output variables. You are using tC as the Celsius temperature, so why not use tF as the calculated Fahrenheit temperature?
Using the calculateAverage example as a guide, you could say:
function tF = tempC2F(tC)
tF=(1.8*tC)+32;
end
That's it. That's your function.
I sincerely appreciate your time and effort in trying to break this down for me and explain the nuances. This WILL work, however when I run the functions and "call" the code:
function tF = tempC2F(tC)
tF=(1.8*tC)+32;
end
in the command window I get the following
>> tC = 100;
tF = tempC2F(tC)
Unrecognized function or variable 'tempC2F'.
I think this has to do with the fact that I have to name the function itself 'tempC2F'... Even though it states in my practice example that the variable names do not have to match the variables used in the function. I'm not exacly sure what I'm doing wrong here. I will accept your answer anyhow, because I believe it best solves the problem I was asking.
I think this has to do with the fact that I have to name the function itself 'tempC2F'... Even though it states in my practice example that the variable names do not have to match the variables used in the function.
These are two different things.
In general, the name of the main function in a function file should have the same name as the file. If they don't match, you will need to use the name of the file to call the function, not the name of the first function. So if you wrote the code function tF = tempC2F(tC) in a file named myTemperatureConverter.m you'd need to call it as tF = myTemperatureConverter(100) rather than tF = tempC2F(100).
The second sentence in the part of your message that I quoted deals with variables, not functions. In general (leaving out things like nested functions or global variables) a function call's workspace is completely independent of what's outside the workspace. If your function defines a variable named x, for example, that's not going to affect or be affected by a variable named x in the workspace in which you call your function. The main ways that data flows into or out of a function are through the input and output arguments.
X = pi
X = 3.1416
callFunctionThatUsesXInternally(42)
X % This didn't change even when the function assigned 42 to X inside its workspace
X = 3.1416
function callFunctionThatUsesXInternally(value)
X = value; % This is independent of the variable on the 1st line of code segment
end
Spaceman
Spaceman on 29 Feb 2024
Edited: Spaceman on 2 Mar 2024
Thank you, my lord. This clears things up. I think the main takeaway here is that a function call's workspace is completely independent of what's outside the workspace.

Sign in to comment.

More Answers (2)

Create a function called tempC2F
function tempC2F
that will accept an input argument of a single temperature in degrees Celsius
function tempC2f(single_temperature_in_degrees_Celcius)
and return the equivalent temperature in degrees Fahrenheit.
function equivelent_temperature_in_degrees_Fahrenheit = tempC2f(single_temperature_in_degrees_Celcius)

6 Comments

This kind of makes sense... Comparing this problem to another I did for practice...
function A = AreaSphere(radius)
A = 4*pi.*radius.^2;
end
% Code to call my function
r=randi(10,3,1);
Area=AreaSphere(r)
I am just having a lot of trouble figuring out what is going on and how this works. After the 'function' command we state the function, (A = AreaSphere(radius)), that explicitly lists part of the call function, (Area=AreaSphere(r)), however, the call function it references has a variable, (r=randi(10,3,1);), that differs from the other variable listed below the 'function' command, (A = 4*pi.*radius.^2;), but THAT one has the 'radius' term that was in the original function. I don't see the correlation or path MATLAB is making to evaluate/call the function.
You've combined two unrelated sections of code in the same file. This code that calls your function would be typed in the Command Window or written in some other file, not in the file that contains AreaSphere as its main function. [I'm intentionally omitting discussion of local functions or functions in script for simplicity right now.]
r = randi(10, 3, 1)
Area = AreaSphere(r) % Call the function
The code that defines your function would be in a function file named AreaSphere.m since the main (first) function in the function file should have the same name as the file itself.
function A = AreaSphere(radius) % Define the function
A = 4*pi.*radius.^2;
end
It can be a little difficult to make the distinction here on MATLAB Answers, since usually we type all the code directly in the Answers editor.
Since it seems like you're fairly new to MATLAB, I suggest you start with the free MATLAB Onramp tutorial to quickly learn the essentials of MATLAB. The Onramp is more interactive than simply reading through documentation pages, so it might better match your learning style. [Some people learn best by reading, some by hearing, some by watching, and some by doing.]
“I am just having a lot of trouble figuring out what is going on and how this works.“
You are overthinking this. Do you know the names of the variables used inside MATLAB function SQRT() ? Answer: no. Does that matter? Answer: no. Can you still call SQRT() with a input of any name? Of course, just like you can with your functions too. Or even no name, simply by writing the input values directly in the function call.
The names of any variables used inside a function definition are totally irrelevant to how you call it. Looking for a relationship that does not exist is just going to confuse you.
I definitely will be utilizing the Onramp tutorial. Thank you Steven and Stephen for your help. I didn't know it was so obvious I am so new, but I can tell everyone here has vast experience in this programming language. I am humbled and eager to learn all I can from all of this and future interactions with you all! Cheers!
I didn't know it was so obvious I am so new
\begin{Yoda mode}
When for more than 20 years you have been answering questions about MATLAB, novice users will you be able to spot :)
\end{Yoda mode}
Hilarious as you are wise XD

Sign in to comment.

So if you want to define them in a single script, the function needs to be at the bottom.
And as others mentioned you might want to check out the documentation on how to define functions. But here is your code arrange to work.
tC = 100;
tF = tempC2F(tC)
tF = 212
function tFahr = tempC2F(tCelcius)
tFahr=(1.8*tCelcius)+32;
end

3 Comments

Genius! This is very helpful, even though it's not quite intuitive to me. Before reading others comments I would of asked why the "function" was named 'tFahr', but inevitably I don't think it matters since we are "calling" the function above.
Just to make sure there are no confusion, here are a couple things that might be helpful to your understanding.
  • The function name is 'tempC2F'
  • The function output is 'tFahr'
  • 'tFahr' variable only lives within the function. Outside of the function, nobody knows what 'tFahr' is (there might be a completely different variable with the same name and that's why you might want to checkout the topic of 'workspaces' here).
  • The syntax matlab uses to define a function is literally how you would use that function from another piece of code with a 'function' attached to the front to define it as a function.
% function definition
function functionOutput = myFunctionName(functionInput)
% whatever the function needs to do,
% in this case it just multiplies the input by 5 and returns that value
functionOutput = 5*functionInput;
end
And to call the function from outside as:
x = myFunctionName(10); % this will make x = 50
  • To call the function, the script that holds the function needs to be in your matlab path. Because it was not in your matlab path you got the error 'Unrecognized function or variable 'tempC2F' 'in previous comments.
This. I actually finally learned about functions and this explains it perfectly. Thank you. I assume when it gets more complicated with loops and such I will be right back here asking questions, lol.

Sign in to comment.

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products

Release

R2023b

Tags

Asked:

on 27 Feb 2024

Commented:

on 2 Mar 2024

Community Treasure Hunt

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

Start Hunting!