Two useful tips for learning MATLAB:
- Get comfortable using the documentation : it has lots of examples and information that will make your own life easier! Learn to navigate the Contents (on the left-hand side of the webpage).
- Learn about vectorization and how to write efficient code right from the beginning, rather than learning poor coding practices first and trying to unlearn them later...
Some examples from your code of how doing these can be useful. These four lines
num1 = zeros(1,30);
for i = 1:30
num1(i) = randi(9);
end
can be entirely replaced with one randi call which is faster, neater and much easier to read!
But there is still a mistake here which we can fix by reading the randi documentation. It states quite clearly that randi(imax) returns a pseudorandom scalar integer between 1 and imax., so your code
will return any of 1,2,3,4,5,6,7,8,9 but excludes 0 because the lower bound of randi is one, not zero. Did you notice that zero is missing? How would you include zero in this list? (Hint: try a different upper bound, and subtract one). This brings us onto one more tip:
- Always check your code as you are writing it! Check that each line does exactly what you want it to do. Do not write a massive amount of code, try to run it, and then get confused because you don't know where the mistake occurs.
To perform the sum you should consider:
- preallocate a vector of zeros to put the sum in.
- use a for-loop to iterate over the length of your vectors.
- start at the ones (the right-end) and add the numbers one at a time.
- take care of any remainders!