Sum using vectorized commands and colon operator instead of loops.
14 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!