Checking for value within boundaries - matlab

I'm trying to create a function that would verify if a value is within chosen boundaries and if it's not, the user must retry until verification.
I wanted to know why my code skips the if condition for any given value and it returns me for the input prompt : "Error: Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error."
A=limit(5pi/6,-pi/2,pi/2) for example jumps directly to the else condition while it's true for the if condition
Here is my code :
function alpha = limit(pos,min,max)
if (pos >= max) && (pos <= min)
alpha=pos;
else
while pos >= max || pos <= min
prompt = 'Enter value between max and min';
alpha = input(prompt);
end
end
end

The function first checks whether pos is both greater than or equal to max and less than or equal to min.
I expect you intend max to be greater than min. Therefore, the if line should be:
if (pos <= max) && (pos >= min)
I assume your val_max/val_min are typos (and should be max/min) Then, your while loop depends on the value of pos. But pos is never updated in the loop, so your loop is just going to iterate forever.
You need to update pos inside the while loop for this to work. Try something like this:
function alpha = limit(pos,min,max)
while pos > max || pos < min
prompt = 'Enter value between min and max';
pos = input(prompt);
end
alpha = pos;
end

Related

Calculating conditional expectation with scipy.stats

Let's suppose x ~ Poisson(2.5); I would like to calculate something like E(x | x > 2).
I assumed that this could be done with the .dist.expect operator, i.e.:
D = stats.poisson(2.5)
cond_expect = D.dist.expect(lambda x: x, D.args,lb=2)
This evaluates to cond_expect = 2.29478750344
However, if I just calculate the mean of a random sample from that distribution
D = stats.poisson(2.5)
test = D.rvs(size = 100000)
empirical_expectation = np.mean(test[test>=2])
empirical_expectation evaluates to 3.20875563063.
If anyone could clarify what I'm misunderstanding about the API, it would be greatly appreciated.
The method expect takes a Boolean parameter conditional, which is False by default. Set it to True:
cond_expect = D.dist.expect(lambda x: x, D.args, lb=2, conditional=True)
returns 3.219839256818051 in agreement with empirical result.
What this does:
conditional : bool, optional
If true then the expectation is corrected by the conditional probability of the summation interval. The return value is the expectation of the function, func, conditional on being in the given interval (k such that ul <= k <= ub). Default is False.
So, if False then you get E(X if X >= 2 else 0) instead of conditional expectation, which is adjusted by division by P(X >= 2): E(X | X >= 2) = E(X if X >= 2 else 0) / P(X >= 2)
I don't know why you would ever want conditional=False when providing an upper or lower bound, but it's the default.

Binary operator "<=" can't be applied to operands of type Bool and Int

if 1 <= A[i] <= 100 || 1 <= B[i] <= 100
for the above line I get these two error.
1. Adjacent operators are in non-associative precedence group 'Comparision Precendence'
2. Binary operator "<=" can not be applied to type BOOL and Int.
try if (1 <= A[i] && A[i] <= 100) || (1 <= B[i] && B[i] <= 100)
Joe's answer and Leo's comment would both work. My preference would be Leo's approach (using 1...100 ~= A[i]), but whatever floats your boat.
That said, let me explain WHY what you did is giving you an error. Without any parenthesis to break it up, it evaluates that going left to right. So if first checks "is 1 <= A[i]?", and that results in a boolean answer. It then tries to ask "is true <= 100?", which makes no sense.

defining a range of values in a while loop

I want to set the while condition to only accept values between 0 and 20?
when I use >20 only, It works but I don't want any values less than 0.
T1 = int(raw_input("Please enter score out of 20: "))
while T1!=(0<T1<20):
print("out of range. Please try again!")
T1 = int(raw_input("Please enter score out of 20: "))
else:
name_array.append(int(T1))
You can use if its >= 1 && <=20 So it could check if its in between 1-20.

define the prompted number is prime or not

i want a code to define the prompted number by user is prime or not . since it's an assignment
i'm not allowed to use ' isprime ' predefined code .
the following approach was not useful :
N = input( 'please enter a positive enteger value = ' ) ;
Quotient = floor(N - (mod(N,2)./2)) ;
for i = 1 : Quotient
if mod(N,i ) == 0
fprintf(' your prompted number is not prime ' ) ;
if mod(N,i) ~= 0
fprintf(' your prompted number is prime ' ) ;
end
end
end
for example if i enter a prime number like 13 it results in this :
your prompted number is prime
but if i enter a Non-prime num like 12 it repeats the ' your prompted number is prime ' message for 10 times .
for i = 1 : Quotient
if mod(N,i ) == 0
That will give you every number since x mod 1 is always zero. In other words, the remainder (when you divide any positive integer by one) is zero, since all of them divide perfectly.
You need to start at 2 rather than 1.
In addition, once you've found out the number is not prime, you should stop the loop since there's no possibility of it becoming prime again after that :-) And, for efficiency, you only need to go up to the square root of the number since, if it has a factor above that, you would have already found the equivalent factor below that.
The pseudo-code for such a beast would be:
set isprime to true
set chkval to 2
while chkval * chkval <= number:
if number mod chkval is zero:
set isprime to false
exit while
end if
increment chkval
end while
if isprime:
say number, " is prime"
else:
say number, " is composite"
Try to find factors and as soon as you find one you know it's not prime:
prime = true
for f = 2:ceil(sqrt(N)) %// Start from 2 as prime numbers DO have 1 as a factor. Anything larger than sqrt(N) will have to have a corresponding factor smaller than this so there is no point checking them
if mod(N,f) == 0
prime = false;
break;
end
end
There are 2 problems with your code. First, as already explained by paxdiablo, you need to start your loop from 2. Secondly you have nested your if statements, and since they are mutually exclusive conditions, the inner condition will never trigger.

set the values to binary

for s=1:length(C_tem)
for w=1:length(C_tem{s})
if (abs(C_tem{s}{w}) >= 0)
C_tem{s}{w} = 1;
else
C_tem{s}{w} = 0;
end
end
end
I am trying to set the values larger than 0 to 1, and if less or equal to 0, but for some reason this doesn't work.
I'm new in matlab, and I really need the help if possible. Thank you in advance..
i havn't worked on matlab much but this part of code feels suspicious -
if (abs(C_tem{s}{w}) >= 0)
C_tem{s}{w} = 1;
else
C_tem{s}{w} = 0;
end
Why are you doing abs here? I think it will remove sign from number. Code should be something like this-
if (C_tem{s}{w} > 0) //I have removed abs and >= is replaced with >
C_tem{s}{w} = 1;
else
C_tem{s}{w} = 0;
end
abs(x)>=0 is true for all values of x. The simple answer is to remove the abs. The more complete answer follows up on Dan's comment. The cell array is unnecessary at the inner level. If you instead had a cell array of regular arrays, then you could do this for the entire block of code.
for s=1:length(C_tem)
C_tem{s} = (C_tem{s} >= 0);
end
Two things to notice: comparison operators are vectorized, meaning they return a matrix of the same size as the input, thus comparing all values at once. And, the output of the operator is 1 where true and 0 where false.
Also look at the builtin function sign to see if that's closer to what you want to do.