Making a decimal output using three binary inputs
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
reza hakimi
le 16 Fév 2023
Réponse apportée : John D'Errico
le 16 Fév 2023
Hello
What tool should I use to make the following pattern in MATLAB?
If A=0, B=0, C=1, the output is equal to 1
If A=1, B=0, C=1, the output is equal to 2
If A=1, B=0, C=0, the output is equal to 3
If A=1, B=1, C=0, the output is equal to 4
If A=0, B=1, C=0, the output is equal to 5
If A=0, B=1, C=1, the output is equal to 6
1 commentaire
Stephen23
le 16 Fév 2023
That looks like a Gray-code: https://en.wikipedia.org/wiki/Gray_code
You should be asking about converting Gray-code. But just for fun:
A = cat(3,[0,5;3,4],[1,6;2,0]);
F = @(a,b,c)interpn(A,a+1,b+1,c+1,'nearest');
F(0,0,1)
F(1,0,1)
F(1,0,0)
F(1,1,0)
F(0,1,0)
F(0,1,1)
Réponse acceptée
John D'Errico
le 16 Fév 2023
If you have only 3 bits, so {A,B,C}, then one simple solution is to use a dictionary. Or you could just use a table lookup. For example...
ABC = {[0 0 1],[1 0 1],[1 0 0],[1 1 0],[0 1 0],[0 1 1]};
out = [1 2 3 4 5 6];
dict1 = dictionary(ABC,out)
And now you can use it to lookup any value.
dict1({[1 1 0]})
But more likely, you will have some more length set of inputs. And since this appears to be a gray code of sorts, at least for the present time, you can use bin2gray and gray2bin.
0 commentaires
Plus de réponses (1)
Arif Hoq
le 16 Fév 2023
do it as a function
a=0;
b=1;
c=1;
out=make_decision(a,b,c)
function output=make_decision(A,B,C)
if A==0 && B==0 && C==1
output=1;
elseif A==1 && B==0 && C==1
output=2;
elseif A==1 && B==0 && C==0
output=3;
elseif A==1 && B==1 && C==0
output=4;
elseif A==0 && B==1 && C==0
output=5;
elseif A==0 && B==1 && C==1
output=6;
end
end
4 commentaires
Stephen23
le 16 Fév 2023
Modifié(e) : Stephen23
le 16 Fév 2023
"Output argument 'output' is not assigned on some execution paths."
Because the output is not defined on all execution paths. Consider A=1, B=1, C=1, is the output defined? (hint: no).
Ergo, if you supply input combinations which do not define an output, then you will get an error.
Arif Hoq
le 16 Fév 2023
Stephen is right. try this
a=1;
b=1;
c=1;
out=make_decision(a,b,c)
function output=make_decision(A,B,C)
if A==0 && B==0 && C==1
output=1;
elseif A==1 && B==0 && C==1
output=2;
elseif A==1 && B==0 && C==0
output=3;
elseif A==1 && B==1 && C==0
output=4;
elseif A==0 && B==1 && C==0
output=5;
elseif A==0 && B==1 && C==1
output=6;
else
output=0;
end
end
If you want to execut it in simulink try it in a Matlab function block
Voir également
Catégories
En savoir plus sur String dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!