User defined with imbedded for loop

8 views (last 30 days)
Jacob Lindsay
Jacob Lindsay on 18 Nov 2019
Answered: Jyothis Gireesh on 21 Nov 2019
I need to create a user defined function that calculates the sum of a vector with a for loop. Then a user defines the array and uses the User defined function to calculate the sum of whatever function. My thoughts were function sum = calcsum(x) for n=1:length(x) sum = 0+x(n) End Display sum End Where x is whatever vector the user says. This doesn’t work because there is not enough input. What do I do?

Answers (1)

Jyothis Gireesh
Jyothis Gireesh on 21 Nov 2019
Here are some suggestions which may be useful:
  • This error may occur due to the input vector not being given as an input argument during function call. One possible solution is to use the following syntax and execute the function from the MATLAB command line using the following syntax
y = calsum(x)
where "x" is the input vector.
  • Yet another solution may be to accept the user input within the function and to return the sum as follows:
function y = calsum()
x = input('Enter the vector: ');
y = 0;
for i = 1:numel(x)
y = y + x(i);
end
end
This can be executed as any normal MATLAB script.

Categories

Find more on Loops and Conditional Statements 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!