Clear Filters
Clear Filters

Sum using vectorized commands and colon operator instead of loops.

12 views (last 30 days)
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.

Accepted Answer

Wayne King
Wayne King on 2 Oct 2013
Edited: Wayne King on 2 Oct 2013
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)

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!