- It seems like the intent of the n is to use it as the upper limit of the for-loop, but the directions then state to hard-code this upper limit at 20, making n useless.
- It uses the variable name "sum" which causes the code to shadow the MATLAB sum( ) function. Best practice is to use a different variable name that doesn't shadow a MATLAB function.

# sum of cubes question

12 views (last 30 days)

Show older comments

Please let me know how to fix my code. I am unable to make mat lab run.

Here is my code so far:

I created a file and saved it as sum_of_cubes.m

for n=1:20

[sum]=sum_of_cubes(n)

end

I created a new live script, then ran it (or attempted to).

sum=0;

[sum]=sum_of_cubes(20)

Please see the homework prompt below.

##### 0 Comments

### Accepted Answer

James Tursa
on 24 Nov 2020

Edited: James Tursa
on 24 Nov 2020

This homework question is poorly written:

Because of these apparently contradictory instructions, I can see how a beginner would get confused. I would advise you to ignore the direction in the first part 3 and use n as the upper limit of the for-loop. So the body of your function code would look like this:

sum = 0; % <-- 2nd part 3 direction

for i=1:n % <-- using n as the upper limit of the for-loop, ignoring 1st part 3 direction

sum = sum + _______; % <-- you fill this in, 2nd part 3 direction

end

Again, "sum" is a poor choice for a variable name, but I am using it because the directions explicitly told you to do so.

The fill-in-the-blank part is not going to be sum_of_cubes(n) as you have currently written it. See if you can figure out what it should be instead. Look at the sum that is written out in the instructions and ask yourself what you should be adding into sum at each iteration. The instructions state "... keep adding the cube of every number ...", so that is your clue as to what should be here.

### More Answers (0)

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!