random number generation to add and subtract

조회 수: 4 (최근 30일)
Ananya Malik
Ananya Malik 2017년 9월 8일
답변: Guillaume 2017년 9월 8일
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
Pal Szabo
Pal Szabo 2017년 9월 8일
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
Ananya Malik 2017년 9월 8일
4-2 = 2. this 2+3(3rd number in array) = 5; 5 -1(last number in array) = 4. It means intermediate results should be positive.

댓글을 달려면 로그인하십시오.

채택된 답변

Pal Szabo
Pal Szabo 2017년 9월 8일
Try this, it works for me.
% invoke myfunction
[firstnum secondnum thirdnum fourthnum]=myfunction
% if the fourth number produced is outside the desired range or zero,
% invoke function again
while (-9<=fourthnum & fourthnum<=9 & fourthnum~=0)==0
[firstnum secondnum thirdnum fourthnum]=myfunction
end
%%here are your numbers
firstnum
secondnum
thirdnum
fourthnum
function [firstnum secondnum thirdnum fourthnum]=myfunction
base1 = [-9:1:-1];
base11 = [1:1:9];
base = [base1 base11];
i=randi(9);
firstnum=base11(i);
ii=randi(18);
secondnum=base(ii);
iii=randi(18);
thirdnum=base(iii);
fourthnum=4-firstnum-secondnum-thirdnum
end

추가 답변 (2개)

KL
KL 2017년 9월 8일
편집: KL 2017년 9월 8일
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
Guillaume 2017년 9월 8일
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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by