How do I define a function which accepts three variables?

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 commentaires

I'll bet if you read the help for functions, you will find the answer directly.
I know the user can input the variables in [] but how do I multiply them together?

Connectez-vous pour commenter.

Réponses (2)

the cyclist
the cyclist le 4 Déc 2016
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.
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 commentaires

I understand this, but the values for length, width and height have to be input by a user when the program is running. I know how to ask the user for each variable individually i.e. input('What is the length of the box?') but was wondering if you could ask what is the length, width and height of the box in one input function by putting something after the question.
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

Connectez-vous pour commenter.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by