User defined with imbedded for loop

10 ビュー (過去 30 日間)
Jacob Lindsay
Jacob Lindsay 2019 年 11 月 18 日
回答済み: Jyothis Gireesh 2019 年 11 月 21 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by