Add the absolute value of the entry to the total if negative, or divide the total by it if positive.
Show older comments
Consider an array x of randomly generated positive and negative integers. Write a script that performs the following iteration: starting with 0 it goes through the entries of x, adds the absolute value of the entry to the total if they are negative or zero and divides the total by the entry otherwise.
I have a random array, and I know that this requires a for loop, but I'm not really sure where to start with that
Answers (2)
Geoff Hayes
on 1 Feb 2015
0 votes
For a homework question, tho seems pretty straightforward. Use rand to create your array of random numbers, and then use a for or while loop to iterate over each element summing or dividing as needed (use an if and else with the appropriate condition to determine what to do).
2 Comments
TG-SOn
on 1 Feb 2015
Geoff Hayes
on 1 Feb 2015
Use length to determine the number of elements in the array, and then iterate over each element from 1 to this length using the for loop.
Star Strider
on 1 Feb 2015
To generate your ‘array x of randomly generated positive and negative integers’, use the randi function. It generates uniformly-distributed random integers that, depending on how you define them, are always greater than or equal to zero. To generate a sequence of 100 integers on the interval [-10, 10], do this:
x = randi(21, 1, 100) - 11;
Categories
Find more on Logical 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!