Scilab - Finding the average of randomly generated numbers with different indices - scilab

Say I have a function that generates random integers between say (1,10).
Then, I define a (for loop) which has 5 iterations.
This (for loop) calls the function defined above, and then it checks the value of the integer generated by the function. Depending on the value of the integer, the variable "cost" is decided.
function integer = UniformInt(a, b)
integer = min( floor( rand()*(b-a) ) + a , b);
endfunction
for i=1:5
x(i) = UniformInt(1,10);
if (x(i)<4) then
cost(i) = 15;
elseif (4<=x(i) && x(i)<=8) then
cost(i) = 27;
else
cost(i) = 35;
end
end
Now, when I run that and find x, say the values generated are:
5.
9.
5.
2.
2.
And so, the different cost values will be:
27.
35.
27.
15.
15.
This is all good so far. Now, what I want to do with these results is:
Check how many times each value of x appeared. I can do this via Scilab's tabul function:
9. 1.
5. 2.
2. 2.
Now, what I really want to code is:
x=9 only showed up once, so, the average of cost is 35/1 = 35.
x=5 showed up twice, so, the average of cost is (27+27)/2 = 27.
x=2 showed up twice, so, the average of cost is (15+15)/2 = 15.
How would I do that?
For posterity, a code in which the answer provided by user #Stéphane Mottelet would be useful (because my code above is trivial) is as follows:
function integer = UniformInt(a, b)
integer = min( floor( rand()*(b-a) ) + a , b);
endfunction
for i=1:5
x(i) = UniformInt(1,10);
if (x(i)<4) then
cost(i) = 15*rand();
elseif (4<=x(i) && x(i)<=8) then
cost(i) = 27*rand();
else
cost(i) = 35*rand();
end
end
Now the cost values are multiplied by a random number, and so,
if the value of say x=10 showed up 2 times, the average cost when x=10 will not simply be (35+35)/2.

I would do like this, but the answer is quite trivial since for now the value of cost is the same for a given x value (I suppose your real application draws random values of cost)
t = tabul(x);
for k = 1:size(t,1)
avg(k) = mean(cost(x == t(k)));
end

Related

Julia UndefVarError on Metaprogramming

I'm trying to do a solver for equations. When I run the code the X variable appears to be undefined, but it prints out perfectly. What am I missing?
I should give the program some numbers, than operations as Macros and it should create an outer product matrix of the operations applied.
function msu()
print("Insert how many values: ")
quantity = parse(Int64, readline())
values = []
for i in 1:quantity
println("x$i")
num1 = parse(Float64, readline())
push!(values, num1)
end
println(values)
print("How many operations? ")
quantity = parse(Int64, readline())
ops = []
for i in 1:quantity
push!(ops, Meta.parse(readline()))
end
mat = zeros((quantity, quantity))
for i in 1:length(mat)
sum = 0
for j in 1:length(values)
# here begins problems, the following prints are for debugging purpose
print(length(values))
func = Meta.parse("$(ops[convert(Int64, ceil(j / quantity))]) * $(ops[convert(Int64, j % quantity)])")
print(func)
x = values[j]
println(x)
sum += eval(func)
end
mat[i] = sum
end
println(mat)
end
msu()
The original code was in Spanish, if you find any typo it's probably because I skipped a translation.

How to find the filter coefficients for a DVBS2 shaping SRRC?

in the DVBS2 Standard the SRRC filter is defined as
How can i find the filter's time domain coefficients for implementation? The Inverse Fourier transform of this is not clear to me.
For DVBS2 signal you can use RRC match filter before timing recovery. For match filter, you can use this expression:
For example for n_ISI = 32 and Roll of factor = 0.25 with any sample per symbol you can use this Matlab code:
SPS = 4; %for example
n_ISI=32;
rolloff = 0.25;
n = linspace(-n_ISI/2,n_ISI/2,n_ISI*SPS+1) ;
rrcFilt = zeros(size(n)) ;
for iter = 1:length(n)
if n(iter) == 0
rrcFilt(iter) = 1 - rolloff + 4*rolloff/pi ;
elseif abs(n(iter)) == 1/4/rolloff
rrcFilt(iter) = rolloff/sqrt(2)*((1+2/pi)*sin(pi/4/rolloff)+(1-2/pi)*cos(pi/4/rolloff)) ;
else
rrcFilt(iter) = (4*rolloff/pi)/(1-(4*rolloff*n(iter)).^2) * (cos((1+rolloff)*pi*n(iter)) + sin((1-rolloff)*pi*n(iter))/(4*rolloff*n(iter))) ;
end
end
But if you want to use SRRC, there are two ways: 1. You can use its frequency representation form if you use filtering in the frequency domain. And for implementation, you can use the expression that you've noted. 2. For time-domain filtering, you should define the FIR filter with its time representation sequence. The time representation of such SRRC pulses is shown to adopt the following form:

Getting a zero value for a variable that clearly should not be zero

I have written the following code to calculate temperature distribution along a fin. For some reason, it keeps calculating certain values as zero, even when they aren't!
for t = 0:300:3000
for i = 2:L2
if i ==2
A(i)= 0.75*rhocp*DX/DT + 3*k/dx;
B(i)= k/dx;
C(i)= 2*k/dx;
D(i)= 0.75*rhocp*(DX/DT)*T(i);
elseif i == L2
A(i)= 0.75*rhocp*DX/DT + 3*k/dx;
B(i)= 2*k/dx;
C(i)= k/dx;
D(i)= 0.75*rhocp*(DX/DT)*T(i);
else
A(i)= 0.75*rhocp*DX/DT + 2*k/dx;
B(i)= k/dx;
C(i)= k/dx;
D(i)= rhocp*(DX/DT)*T(i);
end
P(1) = 0;
Q(1) = T(1);
for i = 2:L2
DENO = A(i) - C(i)*P(i-1);
NUM = D(i)+ C(i)*Q(i-1);
P(i) = B(i)/DENO;
Q(i) = NUM/DENO;
end
for i =L2:-1:2
if i == L2
T(i) = Q(i);
else
T(i) = P(i)*T(i+1) + Q(i);
end
end
T(L1) = ((2*k*T(L2) - h*DX*Tinf)/(2*k - h*DX));
end
disp (T);
`
DENO and NUM is calculated as zero in the first iteration, even though on calculating their values is not zero! This leads to "Division by zero" error.
A(2)-C(2)*P(1)
ans =
3750.
Analytically it has got a value though.
Please give the parameter values so one can run your script...
DT was missing , i set it to 1 .
Finally I found the problem: you forgot an end to close the loop
for i = 2:L2
the end has to be put just before P(1)=0
Moreover this loop does not depend on the t value so it could be put before the loop for t = 0:300:3000

Python 3.6 user-defined board size win check with 2 variables

I have somewhat a general question for more experienced programmers. I'm somewhat new to programming, but still enjoy it quite a bit. I've been working with Python, and decided to try to program a tic tac toe game, but with variable board size that can be decided by the user (all the way up to a 26x26 board). Here's what I've got so far:
print("""Welcome to tic tac toe!
You will begin by determining who goes first;
Player 2 will decide on the board size, from 3 to 26.
Depending on the size of the board, you will have to
get a certain amount of your symbol (X/O) in a row to win.
To place symbols on the board, input their coordinates;
letter first, then number (e.g. a2, g10, or f18).
That's it for the rules. Good luck!\n""")
while True:
ready = input("Are you ready? When you are, input 'yes'.")
if ready.lower() == 'yes': break
def printboard(n, board):
print() #print board in ranks of n length; n given later
boardbyrnk = [board[ind:ind+n] for ind in range(0,n**2,n)]
for rank in range(n):
rn = f"{n-rank:02d}" #pads with a 0 if rank number < 10
print(f"{rn}|{'|'.join(boardbyrnk[rank])}|") #with rank#'s
print(" ",end="") #files at bottom of board
for file in range(97,n+97): print(" "+chr(file), end="")
print()
def sqindex(prompt, n, board, syms): #takes input & returns index
#ss is a list/array of all possible square names
ss = [chr(r+97)+str(f+1) for r in range(n) for f in range(n)]
while True: #all bugs will cause input to be taken for same turn
sq = input(prompt)
if not(sq in ss): print("Square doesn't exist!"); continue
#the index is found by multiplying rank and adding file #'s
index = n*(n-int(sq[1:])) + ord(sq[0])-97
if board[index] in syms: #ensure it contains ' '
print("The square must be empty!"); continue
return index
def checkwin(n, w, board, sm): #TODO
#check rows, columns and diagonals in terms of n and w;
#presumably return True if each case is met
return False
ps = ["Player 1", "Player 2"]; syms = ['X', 'O']
#determines number of symbols in a row needed to win later on
c = {3:[3,3],4:[4,6],5:[7,13],6:[14,18],7:[19,24],8:[25,26]}
goagain = True
while goagain:
#decide on board size
while True:
try: n=int(input(f"\n{ps[1]}, how long is the board side? "))
except ValueError: print("Has to be an integer!"); continue
if not(2<n<27): print("Has to be from 3 to 26."); continue
break
board = (n**2)*" " #can be rewritten around a square's index
for num in c:
if c[num][0] <= n <= c[num][1]: w = num; break
print(f"You'll have to get {w} symbols in a row to win.")
for tn in range(n**2): #tn%2 = 0 or 1, determining turn order
printboard(n, board)
pt = ps[tn%2]
sm = syms[tn%2]
prompt = f"{pt}, where do you place your {sm}? "
idx = sqindex(prompt, n, board, syms)
#the index found in the function is used to split the board string
board = board[:idx] + sm + board[idx+1:]
if checkwin(n, w, board, sm):
printboard(n, board); print('\n' + pt + ' wins!!\n\n')
break
if board.count(" ") == 0:
printboard(n, board); print("\nIt's a draw!")
while True: #replay y/n; board size can be redetermined
rstorq = input("Will you play again? Input 'yes' or 'no': ")
if rstorq in ['yes', 'no']:
if rstorq == 'no': goagain = False
break
else: print("Please only input lowercase 'yes' or 'no'.")
print("Thanks for playing!")
So my question to those who know what they're doing is how they would recommend determining whether the current player has won (obviously I have to check in terms of w for all cases, but how to program it well?). It's the only part of the program that doesn't work yet. Thanks!
You can get the size of the board from the board variable (assuming a square board).
def winning_line(line, symbol):
return all(cell == symbol for cell in line)
def diag(board):
return (board[i][i] for i in range(len(board)))
def checkwin(board, symbol):
if any(winning_line(row, symbol) for row in board):
return True
transpose = list(zip(*board))
if any(winning_line(column, symbol) for column in transpose):
return True
return any(winning_line(diag(layout), symbol) for layout in (board, transpose))
zip(*board) is a nice way to get the transpose of your board. If you imagine your original board list as a list of rows, the transpose will be a list of columns.

Using inttrap and diff to get the length of a curve in Scilab

How can you get the length of the curve down below between 0 and 4*pi? The commands you should use are inttrap and diff. Here is what I have now:
t=linspace(0,4*%pi)
x=(4+sin(a*t)).*cos(3*t)
y=(4+sin(a*t)).*sin(3*t)
z=cos(3*t)
xx=diff(x)
yy=diff(y)
zz=diff(z)
aid=sqrt(xx^2+yy^2+zz^2)
length=inttrap([t],aid)
Getting error message, the last step is not right.
The reason for error message is that t and aid have different sizes. And that is because diff returns a vector with 1 entry fewer than the input. You can see how it works on an example: diff([3 1 5]) is [-2 4].
To fix this, use t(1:$-1), which omits the last entry of t. That is,
len = inttrap(t(1:$-1), aid)
(Please don't use length, which is a function name in Scilab.)
Another problem you have is that diff is just differences, not a derivative. To get the derivative, you need to divide by the step size, which in your case is t(2)-t(1).
Also, the syntax xx^2 is deprecated for elementwise power; use xx.^2 instead
t = linspace(0,4*%pi)
a = 1
x = (4+sin(a*t)).*cos(3*t)
y = (4+sin(a*t)).*sin(3*t)
z = cos(3*t)
step = t(2)-t(1)
xx = diff(x)/step
xy = diff(y)/step
xz = diff(z)/step
aid = sqrt(xx.^2+yy.^2+zz.^2)
len = inttrap(t(1:$-1), aid)

Resources