How do I define a function which accepts three variables?
Show older comments
I need to calculate the volume of a box, so I need to multiply the three variables that are input. the question reads: Define a function called box_volume, which accepts three variables and returns the volume of the box.
2 Comments
John D'Errico
on 3 Dec 2016
I'll bet if you read the help for functions, you will find the answer directly.
Rebekka Price
on 4 Dec 2016
Answers (2)
the cyclist
on 4 Dec 2016
0 votes
It sounds like you need a very basic MATLAB tutorial. This forum is not the best place to start for that. I suggest starting at this page.
Image Analyst
on 4 Dec 2016
Hopefully it's not a homework question but some sort of self-learning you're doing. This is extremely basic. Please read this link.
function volume = box_volume(boxLength, boxWidth, boxHeight)
volume = boxLength * boxWidth * boxHeight;
2 Comments
Rebekka Price
on 4 Dec 2016
Image Analyst
on 4 Dec 2016
You said "I know the user can input the variables" so I assume you knew how to do that already.
Then you said "how do I multiply them together" so I answered that because I thought that was your main/only question.
If you don't know how to ask the user for numbers, then you can use inputdlg(). See this snippet and modify it to accept three numbers instead of two. It should be obvious.
% Ask user for two floating point numbers.
defaultValue = {'45.67', '78.91'};
titleBar = 'Enter a value';
userPrompt = {'Enter floating point number 1 : ', 'Enter floating point number 2: '};
caUserInput = inputdlg(userPrompt, titleBar, 1, defaultValue);
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Convert to floating point from string.
usersValue1 = str2double(caUserInput{1})
usersValue2 = str2double(caUserInput{2})
% Check for a valid number.
if isnan(usersValue1)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
% Convert the default from a string and stick that into usersValue1.
usersValue1 = str2double(defaultValue{1});
message = sprintf('I said it had to be a number.\nTry replacing the user.\nI will use %.2f and continue.', usersValue1);
uiwait(warndlg(message));
end
% Do the same for usersValue2
Categories
Find more on Conversion 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!