How do i calculate a sum using a function?

143 visualizaciones (últimos 30 días)
Jonas Fuglsang Hansen
Jonas Fuglsang Hansen el 14 de Oct. de 2017
Comentada: KL el 15 de Oct. de 2017
Problem description:
Using previous examples make a function with one parameter n, number of integers to sum, and one output, the sum of first n integers: 1+2+3+...+n.
How do i use a function to calculate the sum?
  2 comentarios
KL
KL el 14 de Oct. de 2017
Did you read the documentation? Show us what have you tried, we'd be happy help you
Jonas Fuglsang Hansen
Jonas Fuglsang Hansen el 14 de Oct. de 2017
Yes, i've read the documentation. I haven't tried anything yet, as i have no idea where to start. I don't really understand how to write functions in matlab.

Iniciar sesión para comentar.

Respuesta aceptada

Jan
Jan el 14 de Oct. de 2017
Editada: Jan el 14 de Oct. de 2017
Please take the time to read the "Getting Started" chapters. Matlab's OnRamp helps also very efficient to learn the basics.
Did you heard something about how Gauss has solved this problem with pencil and paper when he was in school? You need some seconds only to get the result of the sum from from 1 to 1000. Remember: Write the list of numbers twice in two rows, one in backward direction:
1 2 3 ... n-1 n
n n-1 n-2 ... 2 1
Now sum them up vertically at first: You get n times the value of n+1. Summing them is n*(n+1). But then you have counted each value twice, so take the half of the result:
n * (n+1) / 2
This takes the same computing time for n=10 or n=10^15. How nice.
Now you have to convert it into a function, but you have learned how to do this already. Welcome to the world of Matlab!
  1 comentario
KL
KL el 15 de Oct. de 2017
+1 for bringing in Gauss summation here, Good one Jan!

Iniciar sesión para comentar.

Más respuestas (2)

jean claude
jean claude el 14 de Oct. de 2017
Editada: jean claude el 14 de Oct. de 2017
as i understand you want to sum 1+2+...n so you can use
function S = Ma_somme(n)
S = 0 ;
for i = 1 : n
S = S + i ;
end
end
  3 comentarios
Jonas Fuglsang Hansen
Jonas Fuglsang Hansen el 14 de Oct. de 2017
Editada: Jonas Fuglsang Hansen el 14 de Oct. de 2017
I've tried to run this code, but i get an error, as n is undefined. Edit: It works now. I just realised i didn't use the same symbol as in the input.
Jan
Jan el 14 de Oct. de 2017
To run a function, you cannot just hit the "Run" button, but you save it to a file and call it from Matlab's command window with providing an input:
Result = Ma_somme(19)
@jean claude: Please consider John's advice in the future. It is an advantage for the student and for the forum. Thanks.

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 14 de Oct. de 2017
Hints
function theSum = ComputeSum(n)
theSum = .......
and check this out, and learn from what you see:
vec = 1 : 10;
Also, are you allowed to use the built-in sum() function? And never use "sum" for the name of your variable or you'll destroy the built-in function.
  6 comentarios
Jonas Fuglsang Hansen
Jonas Fuglsang Hansen el 14 de Oct. de 2017
Ah, okay. So functions in matlab, are like functions everywhere else in math. You can call on the function and write a number in as the input, and then it calculates it and returns the output. In this case, if
function S=sumInt(n)
S=0
for i=1:n
S=S+i
end
end
Then it inserts your input in the line "for i=1:n" and calculates? Thanks for the answer! I think i understand functions better now!
Image Analyst
Image Analyst el 14 de Oct. de 2017
Editada: Image Analyst el 14 de Oct. de 2017
Yes, that should do it.
Since you already got one working version, I'll give my version:
function theSum = ComputeSum(n)
theSum = sum(1:n);
That's it! It uses the built-in sum() function but you didn't specifically disallow it so I used it.
Hint: to fix up your indenting, in the MATLAB editor, type control-a (to select all the code) and then control-i (to fix/standardize the indenting of the lines).
Here's another snippet that might come in handy for you:
% Ask user for one integer number.
defaultValue = 45;
titleBar = 'Enter an integer value';
userPrompt = 'Enter the integer';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Round to nearest integer in case they entered a floating point number.
integerValue = round(str2double(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(integerValue)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
integerValue = defaultValue;
message = sprintf('I said it had to be an integer.\nTry replacing the user.\nI will use %d and continue.', integerValue);
uiwait(warndlg(message));
end
If we're done, then you can click "Accept this answer" on the one best answer (it only works on one).

Iniciar sesión para comentar.

Categorías

Más información sobre Logical 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