I need help writing a matlab function
显示 更早的评论
I need help writing a Matlab function that takes a positive integer n as its argument, and returns the sum of all odd numbers between 1 and n.
1 个评论
Jan
2017-1-15
Please clarify, if this is your homework. If so posting a solution might be counter-productive, because you would cheat if you deliver it. Even if it is a homework question, posting what you have tried so far and asking a specific question would be useful. Because asking for explanations is not a cheating instead of letting others solve your work.
采纳的回答
更多回答(2 个)
Jan
2017-1-13
3 个投票
Do you remember how Gauss calculated the sum over all elements from 1 to n? You can modify the method to use only the pairs of odd numbers. This reduces the compuations drastically and you should never process the dull sum.
3 个评论
@John BG: note that square brackets are not required: sum(1:1:100).
The mlint messages is ""Use of brackets [] is unnecessary." This might also be of interest:
I do not post the solution, because I assume, that this is a homework question. I even did not mention, that asking an internet search engine for the terms "sum of odd numbers" reveals the main part of the solution already: The sum of N odd numbers is N^2.
@Stephen: The step size 1 is not required in vectors, so this is enough: sum(1:100). This does not influence the computing time but is nicer . The leaner the code, the less chances for a typo... :-)
Walter Roberson
2017-1-15
Assuming N odd,
1 + 3 + 5 +... N
N + (N-2) + (N-4) +... 1
Each pair adds to N+1. Count the pairs and multiply by that. Then divide by 2 because each pair is being counted twice.
类别
在 帮助中心 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!