simple for loop // but strange output answer - actionscript-3

I'm trying to understand why the output for z is always -1 whenever I trace the variable. I'm counting coins and I'm trying to set up a for loop, however, I'm always prompted by an error because of z = -1.
for (var z:int = coins.length; z >= 0; z--);
{
trace(z);
trace(coins.length);
}
The output answer I get for these two variables are:
Z = -1
coins.length = 3
Why is this the case? Because all I'm seeing on the output box is:
-1
-1
-1
-1
-1
-1
keeps repeating
If we were to go by the for loop logic, shouldn't the variable z be like this instead?
2
1
0
What can be wrong?

There's your problem:
for (var z:int = coins.length; z >= 0; z--); // the semicolon at the end.
With the semicolon, the loop ends. You wrote a loop without a body. That's perfectly valid and executes just fine.
After the loop, the following code is executed once:
{
trace(z);
trace(coins.length);
}
z is -1, because that's its last value in the loop which causes the loop to stop executing. coins.length never changed and has a value according to the array.
If we were to go by the for loop logic, shouldn't the variable z be like this instead?
2
1
0
No, because it starts at 3, not 2.

Related

MATLAB recursive function [Factorials]

The code works but I am confused. When n==1, I am assigning a=1, shouldn't that overwrite the value and return only 1?
format compact
fct(5)
function a = fct(n)
if n==1
a = 1;
else
a = n*fct(n-1);
end
end
This is how I picture it... Below is a recursion/factorial diagram that shows the cascading effect of the recursive calls. At the deepest recursive call fct(1) is evaluated which is equal to 1 given by the first if statement. Each recursive call is therefore defined by a deeper recursive call. I typically like to decompose the recursive function until reaching its terminating case. I guess a way to phrase it is "a function within function" not so much of a loop.
Where, fct(1) → 1
format compact
fct(5)
function a = fct(n)
if n == 1
a = 1;
else
a = n*fct(n-1);
fprintf("%d\n",a);
end
end
Cumulative/Recursive Results:
2
6
24
120
ans =
120
My Preferred Structuring:
format compact
fct(5)
function a = fct(n)
if n > 1
a = n*fct(n-1);
else
a = n;
end
end

SAS - formula for creation of one column from another

My problem is following - I am creating a column (diskont_faktor) from another one (disc_pc_nonann) with the formula for creation differing based on the row number.
for row #1 the function is diskont_faktor = 1/disc_pc_nonann;
for row #2 to n the function is diskont_faktor = diskont_faktor(t-1)/disc_pc_nonann;
I tried following code:
data soubor2;
set srv.data;
disc_pc_nonann = (1+DISC_PC/100)**(1/12);
if _n_ = 1 then diskont_faktor = 1/disc_pc_nonann;
else diskont_faktor = lag1(diskont_faktor)/disc_pc_nonann;
run;
But SAS does not calculate values for rows > 1.
Is there some specific reason why function lag does not work in this setting of code ?
I tried even this version without success:
data soubor2;
set srv.data;
disc_pc_nonann = (1+DISC_PC/100)**(1/12);
if _n_ = 1 then diskont_faktor = 1/disc_pc_nonann;
else do; y=lag1(diskont_faktor);
diskont_faktor = y/disc_pc_nonann;
end;
run;
Thank you for any advice what I am doing wrong.
The LAG() function does not return the value from the previous observation. Instead it returns the previous value from the stack that it generates as it it is called. So by only executing the lag() for some of the observations you are not properly stacking the values.
One easy way to work around this is to place the value of the LAG() function call into a variable. That way it runs for every observation so it always returns the previous value. You can then conditionally reference the variable if you want without interrupting the stream of values for the LAG() function.
lag_diskont_faktor=lag(diskont_faktor);
if _n_ = 1 then diskont_faktor = 1/disc_pc_nonann;
else diskont_faktor = lag_diskont_faktor/disc_pc_nonann;
But for your problem it looks like you do not really need to use LAG(). You can just use RETAIN to prevent SAS from setting the new variable to missing when it starts the next iteration of the DATA step.
retain diskont_faktor;
if _n_ = 1 then diskont_faktor = 1/disc_pc_nonann;
else diskont_faktor = diskont_faktor/disc_pc_nonann;
You could even set the initial value for the variable in the RETAIN statement and simplify the code.
retain diskont_faktor 1;
diskont_faktor = diskont_faktor/disc_pc_nonann;
You need to initialize your variable diskont_faktor at the start of your program, so add an retain diskont_faktor; at the start.
The first call of lag1 returns you a . , because the queue is empty at that time, so for _n_ = 2 it would return nothing but store your value from _n_= 1 in the queue. _n_ = 3 should work but store your empty result from _n_=2 in the queue. Because for n=2 you had no result, _n_= 4 will return nothing again. This goes on and on, so that you have results for odd _n_ and no result for even _n_.
So i dont know how to solve this whith lag,
but I can provide you an alternative solution without lag:
data soubor2 (drop=diskont_faktor_old);
retain diskont_faktor_old;
set srv.data;
disc_pc_nonann = (1+DISC_PC/100)**(1/12);
if _n_ = 1 then diskont_faktor = 1/disc_pc_nonann;
else diskont_faktor = diskont_faktor_old/disc_pc_nonann;
diskont_faktor_old=diskont_faktor;
run;

Whats wrong with this Code while appending a list with a function?

def listc(favn):
num = 0
while num < favn :
num += 1
return num
list = []
i = int(raw_input("Input your favourite number : > "))
for num in range(0,i):
list.append(listc(i))
print list
The elements of the list are just same. Little iterations in code are sometime printing [None] in list also.
I want to generate a list with content as 1 to i.
There are two issues with your code.
First the while loop does not run 'favn' no. of times because the return statement is within while loop.It just runs single time, and everytime it returns 1.
Also, you should change
for num in range(0,i):
list.append(listc(i))
to
for num in range(0,i):
list.append(listc(num))
You will get the output you wanted.
If you want to generate a list from 1 to i, you can simply do list = range(1, i + 1).

Tips for function inside while loop and i=i+1, Matlab

I have a problem with a function in matlab. This specific function is for filtering light signals. As you can see below I added the coding I’ve used in the function and in the while loop itself. The code is written for a NXT Lego robot.
Is there any tip how to get the count variable ( i = i + 1 ) to work in the function, so we can plot Light(i)? Because we’re getting a bunch of error messages when we try different codes to make it work.
function [light] = filter_func( i)
lightI(i) = GetLight(SENSOR_3);
if i==1
light(i)=lightI(i)
elseif i==2
light(i) = 0.55*lightI(i) + 0.45*lightI(i-1)
else
light(i) = 0.4*lightI(i) + 0.3*lightI(i-1) + 0.3*lightI(i-2);
end
end
i=1
while true
lightI(i) = GetLight(SENSOR_3); % Get’s a lightvalue between 0 and 1024.
if i>2
light =filter_func(i)
light=round(light);
else
light(i) = GetLight(SENSOR_3);;
end
i=1+i
plot(light(end-90:end), 'r-');
title('Lightvalue')
axis([0 100 0 1023]) ;
end
You probably mainly get errors because you are not allowed to mix script and functions like this in MATLAB (like you are in Python).
Your filter function is only used when i>2 so why are you doing the first 2 tests? It seems like you want lightI as a global variable, but that is not what you have done. The lightI inside the function is not the same as the one in the while loop.
Since your while loop runs forever, maybe you don't need to worry about updating the plot the first two times. In that case you can do this:
filter = [0.4 0.3 0.3]';
latest_filtered_light = nan(90,1);
lightI = [];
p = plot(latest_filtered_light, 'r-');
title('Lightvalue')
axis([0 100 0 1023]) ;
while True
lightI(end+1,1) = rand*1024; % Get’s a lightvalue between 0 and 1024.
if i>=3
new_val = lightI(end-2:end,1)'*filter;
latest_filtered_light = [latest_filtered_light(2:end);...
new_val];
set(p, 'ydata', latest_filtered_light)
drawnow
end
end
I think it is an important point to not call plot every time - at least if you are the least concerned about performance.

Function callback ('StopFcn' , 'TimerFcn' )for audiorecorder object in MATLAB? [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
How can I use function callback ('StopFcn' , 'TimerFcn' )for audiorecorder object in MATLAB?
So I try to this code.
% assume fs,winsize,winshift is given.
T = 0.1; % in seconds
samples = cell{100,1};
r = audiorecorder(fs,16,1);
k=1;
r.TimerPeriod = 0.1;
r.StopFcn = 'samples{k} = getaudiodata(r);';
r.TimerFcn = {#get_pitch,samples{k},winsize,winshift};
while 1
record(r,T);
k=k+1;
end
I want to execute the function 'get_pitch(samples,fs,winsize,winshift)' while during recording through audiorecorder object.
But following exception occurs during execution.
1) after record(r,T) is executed. (StopFcn is now called) ??? Error using ==> eval Undefined function or variable 'r'.
2) after StopFcn is called (TimerFcn is now called) In this phase, get_pitch function have totally wrong parameters. For example, parameter in the position samples{k} change to 'audiorecorder object'.
It seems that I do not know exact use of 'StopFcn' & 'TimerFcn'.
Is there anyone who can give me some advice? I really appreciate all of your comments.
Looking at the example in the documentation I would recommend trying to call getaudiodata(r) in your loop rather than with the CallBack. So something like this:
% assume fs,winsize,winshift is given.
T = 0.1; % in seconds
samples = cell{100,1};
r = audiorecorder(fs,16,1);
k=1;
r.TimerPeriod = 0.1;
r.StopFcn = 'disp(''Completed sample '', k)';
r.TimerFcn = {#get_pitch,samples{k - 1},winsize,winshift};
while 1
record(r,T);
samples{k} = getaudiodata(r);
k=k+1;
end
Note I changed the r.TimerFcn to use samples{k - 1} instead of k because k will increment before the timerfcn gets called. So this might give you issues with your first sample, you'll have to tweak it a little. Also this is an infinite loop, which I'm sure you'll want to address.