array a=[8 6 7] adding 0:1 to the array. possible combination for array should be 2^3=8.

the output i want is a matrix of values listed below
x(possible combination)= 8 6 7
8 6 8
8 7 7
8 7 8
9 6 7
9 6 8
9 7 7
9 7 8

 Réponse acceptée

a=[8 6 7];
a+dec2bin(0:2^numel(a)-1)-'0'
ans = 8×3
8 6 7 8 6 8 8 7 7 8 7 8 9 6 7 9 6 8 9 7 7 9 7 8

6 commentaires

and what if i have to add -1:1 to the array a. the combination will be 3^3=27. how do i write code for this?
i am not getting the correct output for -1:1 ?
Use dec2base to convert to base 3 instead of base 2, and substract 1 to make it -1:1 instead of 0:2
a=[8 6 7];
a+dec2base(0:3^numel(a)-1,3)-1-'0'
ans = 27×3
7 5 6 7 5 7 7 5 8 7 6 6 7 6 7 7 6 8 7 7 6 7 7 7 7 7 8 8 5 6
Thanks for your help. can you please explain me in brief how did you write the code?
a=[8 6 6 7 8 6 5 6 6 7 8 6 6 6];
a+dec2base(0:5^numel(a)-2,5)-2-'0'
Requested 6103515624x1 (45.5GB) array exceeds maximum array size preference (7.9GB). This might cause
MATLAB to become unresponsive.
why I am not getting the output?
Well, you already know that the number of rows in the result is b^n where b is the base (in this case 2 or 3) and n is the number of elements you start with. That suggests to me that you also know that counting from 0 to b^n-1 is essentially what the process is. So I start with 0:b^n-1 and convert them to binary or ternary character vectors:
a = [8 6 7]
a = 1×3
8 6 7
dec2base(0:3^numel(a)-1,3)
ans = 27×3 char array
'000' '001' '002' '010' '011' '012' '020' '021' '022' '100' '101' '102' '110' '111' '112' '120' '121' '122' '200' '201' '202' '210' '211' '212' '220' '221' '222'
Then subtract the character '0' to get the distance of each character from the character '0', which is equivalent to its numerical value:
dec2base(0:3^numel(a)-1,3)-'0'
ans = 27×3
0 0 0 0 0 1 0 0 2 0 1 0 0 1 1 0 1 2 0 2 0 0 2 1 0 2 2 1 0 0
Then add that to the original vector a, with adjustment of -1 in base 3 to get -1:1 rather than 0:2.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by