Logical statement with variable gates and true/false vectors without using EVAL

3 ビュー (過去 30 日間)
Hi All! Thank-you for help in advance.
I have a long logical statement of a dozen true/false vectors with eleven logical gates between them. The gates can have any one of the three values selected from:
gate = {'&','|','&~'};
Let me use just two vectors and one gate for simplicity. If I use eval, it is a simple matter of concatenating a string...
tfvect1 = [0;1;0;1;1];
tfvect2 = [1;1;1;1;0];
gate = {'&','|','&~'};
n=1;
tf_result = eval(['tfvect1',gate{n},'tfvect2'])
but I want to avoid EVAL (aka 'EVIL') because I want to compile the code. This is actually the first time ever I've used EVAL, but I can't think of another way. STR2FUNC doesn't interpret a logical statement as valid, that is:
tfvect1 = [0;1;0;1;1];
tfvect2 = [1;1;1;1;0];
gate = {'&','|','&~'};
str='@(hit1,hit2,n)hit1 gate{n} hit2'
tf = str2func(str);
tf(tfvect1,tfvect1,1)
chokes on the logical statement (which MATLAB is happy with if you type it on the command line) - apparently STRFUNC only accepts algebraic statements.
Surely there is a better method than hard coding all the possible permutations of the logical statement? Any ideas please?
  3 件のコメント
Jurgens Wolfaardt
Jurgens Wolfaardt 2017 年 10 月 31 日
Thank-you Walter! Do you mean..
tfvect1 = [0;1;0;1;1];
tfvect2 = [1;1;1;1;0];
gate = {'&','|','&~'};
tf = str2func(sprintf('@(hit1,hit2,n)hit1 %s hit2', gate{n}))
tf(tfvect1,tfvect1,2)
It gives me the same result regardless of 'n' used
Walter Roberson
Walter Roberson 2017 年 10 月 31 日
Sorry, the code is not parameterized by n. You would need different code for full expansion.

サインインしてコメントする。

採用された回答

Sean de Wolski
Sean de Wolski 2017 年 10 月 31 日
How about indexing into the function handles?
gate = {@and, @or, @(x,y)x&~y} %'&','|','&~'};
tfvect1 = [0;1;0;1;1];
tfvect2 = [1;1;1;1;0];
gateidx = [2 3 1];
for ii = numel(gateidx):-1:1
tf(:, ii) = gate{gateidx(ii)}(tfvect1, tfvect2);
end
  4 件のコメント
Jurgens Wolfaardt
Jurgens Wolfaardt 2017 年 10 月 31 日
Oops - its the latter!
Jurgens Wolfaardt
Jurgens Wolfaardt 2017 年 10 月 31 日
Thanks all - this taught me heaps.

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 10 月 31 日
possible_gates = {'&','|','&~'};
andnot = @(a,b) a &~ b;
gatefuns = {@and, @or, andnot};
[~, gateidx] = ismember(gate, possible_gates);
current = gatefuns{gateidx(1)}(tfvect{1}, tfvect{2});
for K = 3 : length(tfvect);
current = gatefuns{gateidx(K-1)}(current, tvfect{K});
end

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by