Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
What is the difference between using a MOVE block instead of a direct connection when an output is just to be assign the input value in a function block diagram?
The "wire" tells you that the boolean value computed by ladder code (AND, OR, ...) on the left, is used on the right. It doesn't cause any "memory" to change. (Your drawing just the wire makes the diagram confusing; you really should show the operators on both ends of the wire.)
The MOVE operator causes the content of one memory location, of any type, to be conditionally copied to another. Using the MOVE operator, you can copy an integer, float or other more complex value to a new destination; I don't recall if you can do a value coercion (e.g., int to float) also but I'd guess that varied from controller to controller. As a side effect, the MOVE operator copies the input boolean on the left side, to the output boolean on the right; most "block" like operators in ladder logic do this. But that input boolean controls whether the block actually does its action, or not. In your example, you show the MOVE block, but not the critical parameters: the from and to locations; the "wire" feeding it controls whether the move actually happens. So a better move example would be:
---| X |------| MOVE(P,Q) |---( Y )---
What this says is, "if X is true, then copy P to Q, and assign true (from X) to Y;
if X is false, move nothing, and assign false(from X) to Y." (The boolean value of X is copied through the MOVE block).
Since MOVE will work with any type, you can use MOVE to copy a boolean value in a memory location to another location; just imagine P and Q above being boolean variables. However, boolean conditions and actions work just as well:
---| X |----( Y )---
copies the boolean value of X to the boolean value of Y.
To truly simulate a boolean MOVE command, e.g., "copy boolean P conditionally to Q if X is true" requires some convoluted boolean logic:
--+--| X |----| P |---+--( Y )----
| |
|--| *X |---| Y |---|
where *X means "not X". MOVE is simply easier to "write".
Related
How to realize open formula in Coq?
I think Coq's Prop means closed formula,
but I also want to use open formula such as x = 0.
If anything, x is in R.
Check x = 0.
(* The reference x was not found in the current environment. *)
Maybe you could define an arbitrary variable x without instantiating it, such as:
Variable x:nat.
Check x = 0.
"open" formulas don't make sense either in Coq or in pen-and-paper logic unless you have an environment to interpret variables. Check term requires indeed a closed term so you'll have to specify a binding for x, for example exists x, x = 0.
I am trying to create a tic-tac-toe program as a mental exercise and I have the board states stored as booleans like so:
http://i.imgur.com/xBiuoAO.png
I would like to simplify this boolean expression...
(a&b&c) | (d&e&f) | (g&h&i) | (a&d&g) | (b&e&h) | (c&f&i) | (a&e&i) | (g&e&c)
My first thoughts were to use a Karnaugh Map but there were no solvers online that supported 9 variables.
and heres the question:
First of all, how would I know if a boolean condition is already as simple as possible?
and second: What is the above boolean condition simplified?
2. Simplified condition:
The original expression
a&b&c|d&e&f|g&h&i|a&d&g|b&e&h|c&f&i|a&e&i|g&e&c
can be simplified to the following, knowing that & is more prioritary than |
e&(d&f|b&h|a&i|g&c)|a&(b&c|d&g)|i&(g&h|c&f)
which is 4 chars shorter, performs in the worst case 18 & and | evaluations (the original one counted 23)
There is no shorter boolean formula (see point below). If you switch to matrices, maybe you can find another solution.
1. Making sure we got the smallest formula
Normally, it is very hard to find the smallest formula. See this recent paper if you are more interested. But in our case, there is a simple proof.
We will reason about a formula being the smallest with respect to the formula size, where for a variable a, size(a)=1, for a boolean operation size(A&B) = size(A|B) = size(A) + 1 + size(B), and for negation size(!A) = size(A) (thus we can suppose that we have Negation Normal Form at no cost).
With respect to that size, our formula has size 37.
The proof that you cannot do better consists in first remarking that there are 8 rows to check, and that there is always a pair of letter distinguishing 2 different rows. Since we can regroup these 8 checks in no less than 3 conjuncts with the remaining variable, the number of variables in the final formula should be at least 8*2+3 = 19, from which we can deduce the minimal tree size.
Detailed proof
Let us suppose that a given formula F is the smallest and in NNF format.
F cannot contain negated variables like !a. For that, remark that F should be monotonic, that is, if it returns "true" (there is a winning row), then changing one of the variables from false to true should not change that result. According to Wikipedia, F can be written without negation. Even better, we can prove that we can remove the negation. Following this answer, we could convert back and from DNF format, removing negated variables in the middle or replacing them by true.
F cannot contain a sub-tree like a disjunction of two variables a|b.
For this formula to be useful and not exchangeable with either a or b, it would mean that there are contradicting assignments such that for example
F[a|b] = true and F[a] = false, therefore that a = false and b = true because of monotonicity. Also, in this case, turning b to false makes the whole formula false because false = F[a] = F[a|false] >= F[a|b](b = false).
Therefore there is a row passing by b which is the cause of the truth, and it cannot go through a, hence for example e = true and h = true.
And the checking of this row passes by the expression a|b for testing b. However, it means that with a,e,h being true and all other set to false, F is still true, which contradicts the purpose of the formula.
Every subtree looking like a&b checks a unique row. So the last letter should appear just above the corresponding disjunction (a&b|...)&{c somewhere for sure here}, or this leaf is useless and either a or b can be removed safely. Indeed, suppose that c does not appear above, and the game is where a&b&c is true and all other variables are false. Then the expression where c is supposed to be above returns false, so a&b will be always useless. So there is a shorter expression by removing a&b.
There are 8 independent branches, so there is at least 8 subtrees of type a&b. We cannot regroup them using a disjunction of 2 conjunctions since a, f and h never share the same rows, so there must be 3 outer variables. 8*2+3 makes 19 variables appear in the final formula.
A tree with 19 variables cannot have less than 18 operators, so in total the size have to be at least 19+18 = 37.
You can have variants of the above formula.
QED.
One option is doing the Karnaugh map manually. Since you have 9 variables, that makes for a 2^4 by 2^5 grid, which is rather large, and by the looks of the equation, probably not very interesting either.
By inspection, it doesn't look like a Karnaugh map will give you any useful information (Karnaugh maps basically reduce expressions such as ((!a)&b) | (a&b) into b), so in that sense of simplification, your expression is already as simple as it can get. But if you want to reduce the number of computations, you can factor out a few variables using the distributivity of the AND operators over ORs.
The best way to think of this is how a person would think of it. No person would say to themselves, "a and b and c, or if d and e and f," etc. They would say "Any three in a row, horizontally, vertically, or diagonally."
Also, instead of doing eight checks (3 rows, 3 columns, and 2 diagonals), you can do just four checks (three rows and one diagonal), then rotate the board 90 degrees, then do the same checks again.
Here's what you end up with. These functions all assume that the board is a three-by-three matrix of booleans, where true represents a winning symbol, and false represents a not-winning symbol.
def win?(board)
winning_row_or_diagonal?(board) ||
winning_row_or_diagonal?(rotate_90(board))
end
def winning_row_or_diagonal?(board)
winning_row?(board) || winning_diagonal?(board)
end
def winning_row?(board)
3.times.any? do |row_number|
three_in_a_row?(board, row_number, 0, 1, 0)
end
end
def winning_diagonal?(board)
three_in_a_row?(board, 0, 0, 1, 1)
end
def three_in_a_row?(board, x, y, delta_x, delta_y)
3.times.all? do |i|
board[x + i * delta_x][y + i * deltay]
end
end
def rotate_90(board)
board.transpose.map(&:reverse)
end
The matrix rotate is from here: https://stackoverflow.com/a/3571501/238886
Although this code is quite a bit more verbose, each function is clear in its intent. Rather than a long boolean expresion, the code now expresses the rules of tic-tac-toe.
You know it's a simple as possible when there are no common sub-terms to extract (e.g. if you had "a&b" in two different trios).
You know your tic tac toe solution must already be as simple as possible because any pair of boxes can belong to at most only one winning line (only one straight line can pass through two given points), so (a & b) can't be reused in any other win you're checking for.
(Also, "simple" can mean a lot of things; specifying what you mean may help you answer your own question. )
From a FP course:
type Set = Int => Boolean // Predicate
/**
* Indicates whether a set contains a given element.
*/
def contains(s: Set, elem: Int): Boolean = s(elem)
Why would that make sense?
assert(contains(x => true, 100))
Basically what it does is provide the value 100 to the function x => true. I.e., we provide 100, it returns true.
But how is this related to sets?
Whatever we put, it returns true. Where is the sense of it?
I understand that we can provide our own set implementation/function as a parameter that would represent the fact that provided value is inside a set (or not) - then (only) this implementation makes the contains function be filled by some sense/meaning/logic/functionality.
But so far it looks like a nonsense function. It is named contains but the name does not represent the logic. We could call it apply() because what it does is to apply a function (the 1st argument) to a value (the 2nd argument). Having only the name contains may tell to a reader what an author might want to say. Isn't it too abstract, maybe?
In the code snippet you show above, any set S is represented by what is called its characteristic function, i.e., a function that given some integer i checks whether i is contained in the set S or not. Thus you can think of such a characteristic function f like it was a set, namely
{i | all integers i for which f i is true}
If you think of any function with type Int => Boolean as set (which is indicated by the type synonym Set = Int => Boolean) then you could describe contains by
Given a set f and an integer i, contains(f, i) checks whether i is an element of f or not.
Some example sets might make the idea more obvious:
Set Characeristic Function
empty set x => false
universal set x => true
set of odd numbers x => x % 2 == 1
set of even numbers x => x % 2 == 0
set of numbeers smaller than 10 x => x < 10
Example: The set {1, 2, 3} can be represented by
val S: Set = (x => 0 <= x && x <= 3)
If you want to know whether some number n is in this set you could do
contains(S, n)
but of course (as you already observed yourself) you would get the same result by directly doing
S(n)
While this is shorter, the former is maybe easier to read (since the intention is somewhat obvious).
Sets (both mathematically and in the context of computer representation) can be represented in various different ways. Using characteristic functions is one possibility. The idea is that a subset S of a given universal set U is completely determined by a function f:U-->{true,false} (called the characteristic function of the subset). simply since you can treat f(u) as answering the question "is u an element in S?".
Any particular choice of representing sets has advantages and disadvantages when compared to other methods. In particular, some representations are better suited to be modeled in a functional language than in imperative languages. If we compare managing sets as characteristic functions vs. as (either sorted or unsorted) lists (or arrays), then, for instance, creating unions, intersections, and set difference, is very efficient with characteristic functions but not so efficient with lists. Checking for the existence of an element is as easy as computing f(-) with characteristic functions, as opposed to searching a list. However, printing out the elements in the set is immediate with a list, but may require lots of computations with a characteristic function.
Having said that, a fundamental difference is that with characteristic functions one can model infinite sets, while this is impossible with array. Of course, no set will actually be infinite, but a set like (x: BigInt) x => (x % 2) == 0 truly represents that set of all even integers and one can actually compute with it (as long as you don't try to print all the elements).
So, every representation has pros and cons (duh).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to read the value of pixcels in image result to compare this value with some
I use to for loop
function GrdImg= GrdLbp(VarImg,mapping,LbpImg)
tic
p=mapping.samples;
[Ysize,Xsize]=size(result);
GImg=zeros(Ysize,Xsize);
temp=[];
cnt=1;
for n=0:p-1
temp(cnt)=2^n;
temp(cnt+1)=(2^p)-1-(2^n);
cnt=cnt+2;
end
for i=1:Ysize
i
for j=1:Xsize
if isempty(find(result(i,j)==temp(:,:)))==1
GImg(i,j)=sqrtm(Vresult(i,j));
end
end
end
but it works too slow, Could you help me what can I use instead of for loop?
Thanks a lot
You didn't really give enough information to answer your question - since, as was stated in the comments, you aren't doing anything with the values in the loop right now. So let me give you a few ideas:
1) To compare all the pixels with a fixed value, and return the index of all pixels greater than 90% of the maximum:
threshold = 0.9 * max(myImage(:));
prettyBigPixels = find(myImage > threshold);
2) To set all pixels < 5% of max to zero:
threshold = 0.05 * max(myImage(:));
myImage(myImage < threshold) = 0;
In the first case, the find command returns all the indices (note - you can access a 2D matrix of MxN with a single index that goes from 1 to M*N). You can use ind2sub to convert to the individual i, j coefficients if you want to.
In the second case, putting (myImage < threshold) as the index of the matrix is called logical indexing - it is very fast, and will access only those elements that meet the criterion.
If you let us know what you're actually doing with the values found we can speed things up more; because right now, the net result of your code is that when the loop is finished, your value Temp is equal to the last element - and since you did nothing in the loop we can rewrite the whole thing as
Temp = pixel(end);
EDIT Now that you show what you are doing in your inner loop, we can optimize more. Behzad already showed how to speed up the computation of the vector temp - nothing to add there, it's the right way to do it. As for the two nested loops, which are likely the place where most time is spent, you can find all the pixels you are interested in with a single line:
pixelsOfInterest = find(~ismember(result(:), temp(:)));
This will find the index of pixels in result that do not occur in temp. You can then do
GImg(pixelsOfInterest) = sqrt(result(pixelsOfInterest));
These two lines together should replace the functionality of everything in your code from for i=1:Ysize to the last end. Note - your variables seem to be uninitialized, and change names - sometimes it's result, sometimes it's Vresult. I am not trying to debug that; just giving you a fast implementation of your inner loop.
As of question completely edited I answer new rather than edit my former answer, by the way.
You can improve your code in some ways:
1. instead of :
for n=0:p-1
temp(cnt)=2^n;
temp(cnt+1)=(2^p)-1-(2^n);
cnt=cnt+2;
end
use this one:
temp=zeros(1,2*p);
n=0:p-1;
temp(1:2:2*p)=2.^n; %//for odd elements
temp(2:2:2*p)=2^p-1-2.^n; %//for even elements (i supposed p>1)
2.when code is ready for calculating and not for debugging or other times, NEVER make some variables to print on screen because it makes too long time (in cpu cycles) to run. In your code there are some variables like i that prints on screen. remove them or end up them by ;.
3.You can use temp(:) in last rows because temp is one-dimensional
4.Different functions are for different types of variables. in this code you can use sqrt() instead of sqrtm(). it may be slightly faster.
5. The big problem in this code is in your last comparison, if non elemnt of temp matrix is not equal with result specific element then do something! its hard to make this part improved unless knowing the real aim of the code! you may be solve the problem in other algorithm that has completely different code. But if there is no way, so use it in this way (nested loops) Good Luck!
It seems your image is grayscle or monocolor , because Temp=pixel(i,j) gives a number not 3-numbers by the way.
Your question has not more explanation so I think in three type of numbers that you are comparison with.
compare with a constant number
compare with a series of numbers
compare with a two dimensional matrix of numbers
If first or third one is your need, solution is very easy (absolutely in third one, size of matrix must be equal to pixel size)
Comparison with a number (c is number or two-dimensional array)
comp=pixel - c;
But if second one is your need, you can first reshape pixel to one-dimensional matrix then compare it with the series of number s (absolutely length of this serie must be equal to product of pixel rows number and columns number; you can re-reshape pixel matrix after comparison to primary two dimensional matrix.
Comparison with a number serie s
pixel_temp = reshape(pixel,1,[]);
comp = pixel_temp - s;
pixel_compared = reshape(pixel_temp,size(pixel,1),size(pixel,2)); % to re-reshape to primary size
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
When I have to work on a portion of an array (elements n to n+m of array A), I never know arrays that I produce from this portion of array A (lets call it B) should start at 1 or n. I could either make B 1) range from elements 1 to m-n or 2) range from n to n+m. On a couple of occasions bugs have been produced from me getting this confused.
If memory is a constraint, then 2) wastes elements 1 to n. On the other hand, it is harder to process A and B together if I do 1) and end up needing to use different indices.
What are the benefits of each method when programming in MatLab?
There are benefits to always start array indexes with zero. While it's a matter of convention, it is a convention that in my experience minimizes error, especially when used in conjunction with closed-below, open-above intervals like [a, b). The length of such an interval is b - a. Since no 1s are involved in the expression, I can't forget to put them in. The interval [0, length) is the whole array: again, no need for 1s. Offsets like [x, x + sublen) also don't need any 1s. With 1-based indexing, combining offsets like x1, x2, x3 requires careful handling of 1s.
While some of these features can be obtained in 1-based indexing with closed-above intervals, not all of them can. When an entire framework adopts the zero-based index, closed-below, open-above convention, like most of C, Python, Java, etc., then you can happily avoid thinking about missing + 1 and - 1 errors in all of your function calls, which is a big help.
I remember having the choice to use any base for an index in Fortran (0, 1, -5, whatever). In the few cases where it was helpful (usually for making indexes symmetric around 0), the same effect could have been achieved by wrapping the array retreival in a function call. Since those cases almost always involved modelling a continuous variable by a grid, I often wanted to make the grid spacing different from 1 and interpolate between the points, too, and for that I absolutely needed to wrap it in a function call anyway.
I didn't know that Matlab gave you a choice (you're talking about Matlab, right?), but it would make sense, given Matlab's relationship to Fortran. The above argument has nothing to do with optimization, but if I'm understanding you right and Matlab fills in unused indexes with some kind of placeholder, then zero-based indexing would avoid that, too (as well as bugs associated with unintentionally using the placeholder as though it were real).