Can't use a second function inside the main one

4 views (last 30 days)
Hello! I've been trying to fix this for over a day now (I'm a begginner in mathlab) and I've not been able to get this piece of code to work.
Basically, i've got 2 functions. The first one asks for values and, after calling the second function, processes the values received.
This is the main function:
function [x, invert] = func(number)
x = input('insert an integer bigger than 0: ');
while x < 0 || mod(x, 1)~=0
x = input('insert again: ');
end
matri = ones(1, x);
k = 1;
while k <= x
sub;
matri = number * matri(k);
k = k + 1;
end
invert = matri(end:-1:1);
end
The second function is this:
function [number] = sub
w = input('insert a number: ');
if w > 100
number = w/3;
else
number = w/2;
end
end
And to call them, i use this script:
func;
[number] = sub;
[invert] = func(number);
disp(invert);
When I run the script, I get asked to input the values and then I get this error: "Error using func (line 15). Not enough input arguments.". I've looked many times into the code, but I can't understand whats missing.
In that specific line I'm trying to grab the number returned by the second function and store it in a matrix.
Any help is appreciated!

Accepted Answer

Steven Lord
Steven Lord on 14 Nov 2018
while k <= x
sub;
matri = number * matri(k);
k = k + 1;
end
When your main function func calls your function sub on the second line of that code segment, it calls sub with 0 input arguments and 0 output arguments. The sub function prompts the user to enter a number using the input function, uses that input to calculate a variable number, then promptly throws that result away at the end of its execution. The sub function offers that information to its caller, but its caller says "I didn't ask you for that, just throw it in the trash."
If you want sub to pass the value it calculated and stored in the variable number to its calling function, you need to define sub to return number as an output (which you did) and you will need its calling function to call it with an output argument (which you did not.) So modifying your main function slightly:
while k <= x
thenum = sub;
matri = thenum * matri(k);
k = k + 1;
end
Note that the name of the variable inside the sub function does not need to match the name of the variable in which the calling function stores that output.

More Answers (1)

madhan ravi
madhan ravi on 14 Nov 2018
Edited: madhan ravi on 14 Nov 2018
number = sub;
invert = func(number);
disp(invert);
your code
func; -> which needs an input here , this line was superfluos
[number] = sub;
[invert] = func(number);
disp(invert);

Categories

Find more on Language Support in Help Center and File Exchange

Products


Release

R2015a

Community Treasure Hunt

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

Start Hunting!