random number generation to add and subtract
Show older comments
I want to create an array of 4 single digit numbers in the range [-9,9] without 0. Addition of these 4 numbers should result in a positive number within 0-9 range. for ex. a= [4,-2,3,-1] =4. However 1st number should be compulsorily positive. And subsequent addition/subtraction should be valid.(i.e. negative number should be subtracted from a positive number). Any help would be greatly appreciated.
So far I have tried this:
a= randi([-9,9],4,1);
if sum(a)>=0 && sum(a)<9
a'
end
2 Comments
Pal Szabo
on 8 Sep 2017
What you mean by this? "And subsequent addition/subtraction should be valid.(i.e. negative number should be subtracted from a positive number)."
Ananya Malik
on 8 Sep 2017
Accepted Answer
More Answers (2)
numsum = -1;
while numsum<0 || numsum>9
a = randi([1 9]);
b = randi([-9 9],3,1);
while b(1)==0 || b(2)==0 || b(3)==0
b = randi([-9 9],3,1)
end
num = [a;b];
numsum = sum(num);
end
Guillaume
on 8 Sep 2017
Another option:
numbers = -1;
while sum(numbers) < 0 | sum(numbers) > 9 | any(cumsum(numbers) < 0)
numbers = randi([1 9], 1, 4) .* (-1).^[2, randi([1 2], 1, 3)];
end
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!