MATLAB: How to call the function which contains input functions

functionpyramid

I have a function pyramid and I want to call it on another script.
Following is my code for the function pyramid:
function [S] = pyramid(V,H)
V= input('Enter the value of volume of square pyramid:');
H=input('Enter the value of height of square pyramid:');
S= sqrt(3*V/H);
fprintf('The lenght of the side of square pyramid is: %d\n',S)
When I called the function, pyramid(7,3) then I have to enter the value of V and H again but I do not want to enter it again because I put the value 7 and 3 of V and H.
How to solve this problem?
Thank you very much

Best Answer

Best approach:
Do not put input statements in functions that are going to be called repeatedly.
But if you must, then:
function [S] = pyramid(V,H)
if ~exist('V', 'var') || isempty(V)
V = input('Enter the value of volume of square pyramid:');
end
if ~exist('H', 'var') || isempty(H)
H = input('Enter the value of height of square pyramid:');
end
S = sqrt(3*V/H);
fprintf('The length of the side of square pyramid is: %f\n',S);
end
Then if you call pyramid without passing any parameters then it will prompt you for the parameters, and if you pass in parameters then it will use them.
Related Question