Making a decimal output using three binary inputs
1 次查看(过去 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
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)
F(1,0,1)
F(1,0,0)
F(1,1,0)
F(0,1,0)
F(0,1,1)
采纳的回答
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)
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 个评论
更多回答(1 个)
Arif Hoq
2023-2-16
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 个评论
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
2023-2-16
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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1297555/image.png)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!