Could someone teach me how to add numbers in a series?
조회 수: 8 (최근 30일)
이전 댓글 표시
Currently my engineering professor has done very little to teach us anything about how to use matlab, and I feel like I am stumbling through the dark on some of the more complex problems he is giving us. Enough of that! My current problem is using the Leibniz Formula. He wants us to write a program that will add a given number of terms together from 1:n.
ex: The sum of the terms to add is: 3
(4-(4/3)+(4/5))=3.46666666667
I would really like a push in the right direction, not an answer.
Thanks!
댓글 수: 0
답변 (2개)
Wayne King
2013년 3월 14일
Welcome to MATLAB! Spend some time reading the MATLAB Getting Started guide. That will help you a lot.
In MATLAB, the key is to represent a sequence of numbers like you have above in an array
X = [4 -4/3 4/5];
Now many MATLAB functions operate naturally on arrays of various sizes and dimensions. For example, read the help for sum()
Y = sum(X)
댓글 수: 0
Carlos
2013년 3월 14일
Consider the Euler series to sum pi:
((pi^2)/6)=∑ (1/n^2),then pi= sqrt(6*∑ (1/n^2))
To implement the above method in Matlab you cand do
>> aux=0; %initialize a variable to zero
for k=1:1:10000 % n goes from 0 to 10000
aux=aux+(1/(k^2)); % ∑ (1/n^2)
end
pi2=sqrt(6*aux)
pi2 =
3.1415
Hope it helps.
댓글 수: 3
Jan
2013년 3월 21일
It surprises me frequently, that so many beginners include a "clear all, clc" in their code. It seems like your professor has not only "done very little to teach us anything about how to use matlab", but the few things he told you, are inefficient wasters of time also. "clear all" removes, beside other things, all loaded function from the memory. Reloading them from disk and parsing them is very time-consuming in Matlab, becaus ethe harddisk access and the code-analysis are expensive. Nevertheless, the brute clean up seems to be a fashion, and instructors teach this, because they have been taught this already. But the opinion of the majority is no necessarily useful of efficient.
There is no limit of the minus operation. Matlab does not get tired or something like that. The problem is, that double values can store integers only up to a range to 2^52 exactly, because there is only space for about 16 digits in the 8 bytes used to store a double. Inside a loop you can reduce the chance to collide with this limitation. So I strongly suggest to try a FOR loop instead, although it might be confusing at first.
참고 항목
카테고리
Help Center 및 File Exchange에서 Entering Commands에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!