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 个评论
John D'Errico
2016-12-3
I'll bet if you read the help for functions, you will find the answer directly.
Rebekka Price
2016-12-4
回答(2 个)
the cyclist
2016-12-4
0 个投票
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
2016-12-4
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 个评论
Rebekka Price
2016-12-4
Image Analyst
2016-12-4
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
类别
在 帮助中心 和 File Exchange 中查找有关 Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!