Sum using vectorized commands and colon operator instead of loops.

14 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Wayne King
Wayne King il 2 Ott 2013
Modificato: Wayne King il 2 Ott 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)

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by