Making a decimal output using three binary inputs

3 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2023-2-16
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)
ans = 1
F(1,0,1)
ans = 2
F(1,0,0)
ans = 3
F(1,1,0)
ans = 4
F(0,1,0)
ans = 5
F(0,1,1)
ans = 6

请先登录,再进行评论。

采纳的回答

John D'Errico
John D'Errico 2023-2-16
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)
dict1 =
dictionary (celldouble) with 6 entries: {[0 0 1]} ⟼ 1 {[1 0 1]} ⟼ 2 {[1 0 0]} ⟼ 3 {[1 1 0]} ⟼ 4 {[0 1 0]} ⟼ 5 {[0 1 1]} ⟼ 6
And now you can use it to lookup any value.
dict1({[1 1 0]})
ans = 4
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.

更多回答(1 个)

Arif Hoq
Arif Hoq 2023-2-16
do it as a function
a=0;
b=1;
c=1;
out=make_decision(a,b,c)
out = 6
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 个评论
Stephen23
Stephen23 2023-2-16
编辑:Stephen23 2023-2-16
"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
Arif Hoq 2023-2-16
Stephen is right. try this
a=1;
b=1;
c=1;
out=make_decision(a,b,c)
out = 0
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Simulink 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by