User defined with imbedded for loop

10 visualizaciones (últimos 30 días)
Jacob Lindsay
Jacob Lindsay el 18 de Nov. de 2019
Respondida: Jyothis Gireesh el 21 de Nov. de 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?

Respuestas (1)

Jyothis Gireesh
Jyothis Gireesh el 21 de Nov. de 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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by