User defined with imbedded for loop

8 次查看(过去 30 天)
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?

回答(1 个)

Jyothis Gireesh
Jyothis Gireesh 2019-11-21
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by