User defined with imbedded for loop

7 Ansichten (letzte 30 Tage)
Jacob Lindsay
Jacob Lindsay am 18 Nov. 2019
Beantwortet: Jyothis Gireesh am 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?

Antworten (1)

Jyothis Gireesh
Jyothis Gireesh am 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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by