필터 지우기
필터 지우기

Sum using vectorized commands and colon operator instead of loops.

조회 수: 8 (최근 30일)
David
David 2013년 10월 2일
댓글: David 2013년 10월 2일
So, first of all I better say that this isn't a homework assignment. It's a sheet of problems given to us which we can attempt in our own time to help get a feel for the final exam. The problem asks you to compute the sum of 1/(k)^3 from 1 to 1000 without using loops. I can't actually afford MATLAB on my laptop and currently am not in college, so I can't test this code but this is what I came up with off the top of my head:
x = [1:1000]; %creates vector of 1 - 1000
x(1:1000) = 1/(x(1:1000))^3; %replaces each element of that array with the inverse cubed of said %element
a = Sum(x); %Sums up all the values of the new x
disp(a) %displays the value of the sum.
So, does the above code actually make sense of have I gone wrong somewhere? Thanks in advance.

채택된 답변

Wayne King
Wayne King 2013년 10월 2일
편집: Wayne King 2013년 10월 2일
Yes, it basically makes sense although what you have would not actually work in MATLAB because you need the "dot" operator for element-by-element operations.
And you have some unnecessary code
k = 1:1000;
y = 1./k.^3;
sum(y)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by