Displaying a table with two columns in Fortran with available data - fortran

I have two variables say x and y and both have around 60 points in them(basically values of the x and y axis of the plot). Now when I try to display it in the result file in form of a column or a table with the x value and the corresponding y value I end up with all the x values displayed in both the columns followed then by the y values. I am unable to get it out correctly.
This is a small part of the code
xpts = PIC1(1,6:NYPIX,1)
ypts = PIC1(2,6:NYPIX,1)
write(21,*), NYPIX
write(21,"(T2,F10.4: T60,F10.4)"), xpts, ypts
This is the output I get. the x values continue from the column 1 to 2 till all are displayed and then the y values are displayed.
128.7018 128.7042
128.7066 128.7089
128.7113 128.7137
128.7160 128.7184
128.7207 128.7231
128.7255 128.7278
128.7302 128.7325
128.7349 128.7373
128.7396 128.7420
128.7444 128.7467
128.7491 128.7514
128.7538 128.7562
128.7585 128.7609
128.7633 128.7656
128.7680 128.7703
128.7727 128.7751
128.7774 128.7798
128.7822 128.7845
128.7869 128.7892
128.7916 128.7940
128.7963 128.7987
128.8011 128.8034
86.7117 86.7036
86.6760 86.6946
86.6317 86.6467
86.6784 86.8192
86.8634 87.0909
87.2584 87.6427
88.1245 88.8343
89.5275 90.2652
91.0958 91.8668
92.6358 93.2986
93.8727 94.4631

You could use a do loop:
do i=1,size(xpts)
write(21,"(T2,F10.4: T60,F10.4)"), xpts(i), ypts(i)
enddo

There is already an answer saying how to get the output as wanted. It may be good, though, to explicitly say why the (unwanted) output as in the question comes about.
In the (generalized) statement
write(unit,fmt) xpts, ypts
the xpts, ypts is the output list. In the description of how the output list is treated we see (Fortran 2008 9.6.3)
If an array appears as an input/output list item, it is treated as if the elements, if any, were specified in array element order
That is, it shouldn't be too surprising that (assuming the lower bound of xpts and ypts are 1)
write(unit, fmt) xpts(1), xpts(2), xpts(3), ..., ypts(1), ypts(2), ...
gives the output seen.
Using a do loop expanded as
write(unit, fmt) xpts(1), ypts(1)
write(unit, fmt) xpts(2), ypts(2)
...
is indeed precisely what is wanted here. However, a more general "give me the elements of the arrays interleaved" could be done with an output implied-do:
write(unit, fmt) (xpts(i), ypts(i), i=LBOUND(xpts,1),UBOUND(xpts,1))
(assuming that the upper and lower bounds of ypts are the same as xpts).
This is equivalent to
write(unit, fmt) xpts(1), ypts(1), xpts(2), ypts(2), ...
(again, for convenience switching to the assumption about lower bounds).
This implied-do may be more natural in some cases. In particular note that the first explicit do loop writes one record for each pair of elements from xpts and ypts; for the implied-do the new record comes about from format reversion. The two for the format in the question are equivalent, but for some more exotic formats the former may not be what is wanted and it ties the structure of the do loop to the format.
This splitting of records holds even more so for unformatted output (which hasn't format reversion).

Related

How to generate derivative list with frequencies

I have some C++ code that picks a random item from a list. I need it to weight that randomness so that an item at place "n" has a chance equal to x/n where "x" is the chance that item one in the list will be selected. My current code is like this:
srand(time(NULL));
string a[≈9000] = {"String#1", "String#2", . . ., "String #≈9000"};
int value = rand() % ≈9000;
cout << a[value]
Note that the number notated as "≈9000" is a precise integer obscured for confidentiality. Variable names may be changed.
How can I weight it? I've come up with an equivalent formula
List B[≈9000] = "Item 'n' of 'a' times ≈9000 ÷ n"
Though you might notice that that isn't accurate CPP notation. Do y'all have any ideas how I can implement this?
This is not possible.
You need somehow to allow a variation on your conditions to have a proper distribution.

How to perform rolling window calculations without SSC packages

Goal: perform rolling window calculations on panel data in Stata with variables PanelVar, TimeVar, and Var1, where the window can change within a loop over different window sizes.
Problem: no access to SSC for the packages that would take care of this (like rangestat)
I know that
by PanelVar: gen Var1_1 = Var1[_n]
produces a copy of Var1 in Var1_1. So I thought it would make sense to try
by PanelVar: gen Var1SumLag = sum(Var1[(_n-3)/_n])
to produce a rolling window calculation for _n-3 to _n for the whole variable. But it fails to produce the results I want, it just produces zeros.
You could use sum(Var1) - sum(Var1[_n-3]), but I also want to be able to make the rolling window left justified (summing future observations) as well as right justified (summing past observations).
Essentially I would like to replicate Python's ".rolling().agg()" functionality.
In Stata _n is the index of the current observation. The expression (_n - 3) / _n yields -2 when _n is 1 and increases slowly with _n but is always less than 1. As a subscript applied to extract values from observations of a variable it always yields missing values given an extra rule that Stata rounds down expressions so supplied. Hence it reduces to -2, -1 or 0: in each case it yields missing values when given as a subscript. Experiment will show you that given any numeric variable say numvar references to numvar[-2] or numvar[-1] or numvar[0] all yield missing values. Otherwise put, you seem to be hoping that the / yields a set of subscripts that return a sequence you can sum over, but that is a long way from what Stata will do in that context: the / is just interpreted as division. (The running sum of missings is always returned as 0, which is an expression of missings being ignored in that calculation: just as 2 + 3 + . + 4 is returned as 9 so also . + . + . + . is returned as 0.)
A fairly general way to do what you want is to use time series operators, and this is strongly preferable to subscripts as (1) doing the right thing with gaps (2) automatically working for panels too. Thus after a tsset or xtset
L0.numvar + L1.numvar + L2.numvar + L3.numvar
yields the sum of the current value and the three previous and
L0.numvar + F1.numvar + F2.numvar + F3.numvar
yields the sum of the current value and the three next. If any of these terms is missing, the sum will be too; a work-around for that is to return say
cond(missing(L3.numvar), 0, L3.numvar)
More general code will require some kind of loop.
Given a desire to loop over lags (negative) and leads (positive) some code might look like this, given a range of subscripts as local macros i <= j
* example i and j
local i = -3
local j = 0
gen double wanted = 0
forval k = `i'/`j' {
if `k' < 0 {
local k1 = -(`k')
replace wanted = wanted + L`k1'.numvar
}
else replace wanted = wanted + F`k'.numvar
}
Alternatively, use Mata.
EDIT There's a simpler method, to use tssmooth ma to get moving averages and then multiply up by the number of terms.
tssmooth ma wanted1=numvar, w(3 1)
tssmooth ma wanted2=numvar, w(0 1 3)
replace wanted1 = 4 * wanted1
replace wanted2 = 4 * wanted2
Note that in contrast to the method above tssmooth ma uses whatever is available at the beginning and end of each panel. So, the first moving average, the average of the first value and the three previous, is returned as just the first value at the beginning of each panel (when the three previous values are unknown).

Python - lambda in list comprehension gives wrong result

I got a numpy.ndarray of electromagnetic samples as complex numbers, where the format is as follows:
ex1:
[[ 8.23133235e-15, -1.59200901e-15, -4.39818917e-13, 7.68089585e-13]
[ 6.98151957e-15, -1.20306059e-15, 9.83923013e-13, 1.64838108e-11]
[ 8.41053742e-15, -1.77702007e-15, -5.98961364e-13, 8.97436205e-13]
[ 7.08443026e-15, -1.25262430e-15, 1.11415868e-12, 1.69346186e-11]]
where rows make up real and imaginary part alternately:
[[z1Ex.real, z1Ey.real, z1Hx.real, z1Hy.real],
[z1Ex.imag, z1Ey.imag, z1Hx.imag, z1Hy.imag],
[z2Ex.real, z2Ey.real, z2Hx.real, z2Hy.real],
[z2Ex.imag, z2Ey.imag, z2Hx.imag, z2Hy.imag],
...etc.]
What I want is to create a new array which expresses the data in magnitude and phase, but keep the same format (i.e. replace real rows with magnitude rows and imaginary with phase rows).
I managed to put up list comprehensions for both calculations (which I´m fairly proud of, being an 2-week amateur, so please be gentle;)). The result for magnitude is what I´d expect, but the phase is terribly off and I don´t have any idea why...
My approach:
Slice the original array in real and imag sub-arrays:
import numpy, cmath
real = ex1[::2] #numpy.ndarray
imag = ex1[1::2] #numpy.ndarray
Define lambdas outside of list comprehension:
magcalc = lambda z, y: abs(complex(z, y))
phasecalc = lambda z,y: cmath.phase(complex(z, y))
Define list comprehension to do math on sub-arrays:
real[:] = np.array([[magcalc(z,y) for z, y in zip(real[x],imag[x])] for x in xrange(len(real))])
imag[:] = np.array([[phasecalc(z,y) for z, y in zip(real[x],imag[x])] for x in xrange(len(imag))])
Check results in original array:
print ex1[:4]
If I do that, the phase result for the first Ex sample is 0.574 rad. If I check the phase manually (i.e. cmath.phase(complex(z1Ex.real,z1Ex.imag))), then I get 0.703 rad. I would accept if there was smth wrong in my list comprehensions, but the magnitude results are completely correct, so I doubt that that´s it.
Where am I doing it wrong? I really tried to find out for 2 days straight now, no luck... Also, I can´t think of another way to achieve what I want.
Please help... (Using Python 2.7)
Thanks
Nils
Oh jeez.. Now I saw the problem, can´t believe how dense I am... Credit goes to John, for making me re-think variable assignments.
In imag[:] = np.array([[phasecalc(z,y) for z, y in zip(real[x],imag[x])] for x in xrange(len(imag))]), I refer to real[], as if it was still populated with real values. But I changed real[] the line before to contain magnitude... So, just changing the variable names for the list comprehensions will do it:
Define list comprehension to do math on sub-arrays:
realcopy[:] = np.array([[magcalc(z,y) for z, y in zip(real[x],imag[x])] for x in xrange(len(real))])
imagcopy[:] = np.array([[phasecalc(z,y) for z, y in zip(real[x],imag[x])] for x in xrange(len(imag))])
And then re-assign to original mag, phase arrays:
Check original results
real[:] = realcopy
imag[:] = imagcopy
print ex1[:4]
Sorry for the waste of time and bytes...
Cheers
Nils

Create a table using arrays [closed]

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
Our profeesser assigned this project but Im at a loss of how to do it. Normally I would figure it out on my own but Ive got a massive English paper due on the same day and I have to finish that also this weekend. The program is due on 11/12/13 but can be turned in by 11/19/13 with a 20% penalty to grade.
Write and test a C++ program to complete the following project:
Generate a table of numbers for use in a math problem.
Ask the user for three numbers:
The first number represents how many values are to be in the table (1
to 25).
The second number represents the first value in the table. (-1000 to
+1000)
The third number represents the increment between successive values
in the table. (1 to 20)
Iterate through the selected values, generating and saving the following derived values from each value in the iteration:
Square
Square Root (only if the value is positive or zero, display “N/A” for
all other values)
Cube
Cube Root (only if the value is positive or zero, display “N/A” for
all other values)
Whether the number is even or odd
Whether the number is prime or not (Prepare a user-defined function
based on the logic in Assignment 5).
Save the results of the calculations in a set of arrays, one array for each calculated value.
After all values are calculated and saved, display the values in a tabular form with one column for each calculated value and a row for each set of values (corresponding to the first value read from the user).
Note that for each negative value in the first column, display “N/A” in the columns for square root and cube root.
Display “Even” or “Odd” for each number’s even/odd status. Display “True” or “False” for the number’s prime-ness.
Repeat this process until the user enters a count of zero for the number of values in the table.
Bonus: Read a series of three-number sets from a data file named triples.txt and create a table of numbers corresponding to each three-number set. Save the resulting tables of numbers to a single text file named numbers.csv in comma-separated-value format.
Heres' what i have so far:
// TABLEation.cpp : builds a table based on user input.
//
using namespace std;
double square, squareroot,cube,cuberoot;
int initialValue,display,increment;
string even,prime;
const int SIZE=25;
int Value[SIZE];
bool isEven( int integer )
{
if ( integer % 2== 0 )
return true;
else
return false;
}
bool isPrime(int testValue) {
int divisor=0, remainder=0;
if (testValue<2) return false;
for(divisor=2; divisor<=sqrt(testValue);divisor++){
if((testValue % divisor)==0) return false;
}
return true;
}
int _tmain()
{
do{
begining:
cout<<"Enter how many values to show (1-25)."<<endl;
cin>>display;
if((display>0) && (display<=25)){
cout<<"Enter an initial Value (-1000 to 1000)."<<endl;
cin>>initialValue;
}
else{
cout<<"ERRROR! INVALID INPUT!TRY AGAIN"<<endl;
goto begining;
}
if ((initialValue>= -1000) && (initialValue<=1000)){
cout<<"Enter a number to increment by (1-20)"<<endl;
cin>>increment;
}
else{
cout<<"ERRROR! INVALID INPUT!TRY AGAIN"<<endl;
goto begining;
}
}
system("pause");
return 0;
}
where should I go from here?
Since there is no question above I am guessing you want someone to either give you the answer, or give you hints towards the right direction. I am going to pretend you are after the latter. The problem is fairly straightforward.
Generate a table of numbers for use in a math problem.
Ask the user for three numbers:
The first number represents how many values are to be in the table (1 to 25).
he second number represents the first value in the table. (-1000 to +1000)
The third number represents the increment between successive values in the table. (1 to 20)
Since below we see that you are to ask these questions in a loop until the first answer is 0 you could build a function "bool get_input(int &num_values, int &start_num, int &increment)" This function will return false if the user puts in a value that is not within the ranges and true otherwise. Now call this function in a while loop where you exit if the num_values is 0.
Iterate through the selected values, generating and saving the following derived values from each value in the iteration:
This is a for loop where i = start_num and at each iteration you increase i+=increment
for each iteration of your for loop you should be calling the following six functions:
Square
int square(int i) which returns the square of the value.
Square Root (only if the value is positive or zero, display “N/A” for all other values)
bool extract_square_root(int i, float &square_root) which returns false if the value is negative, otherwise it puts the square root into the reference variable.
Cube
int cube(int i) which returns the cube of the value.
Cube Root (only if the value is positive or zero, display “N/A” for all other values)
bool extract_cube_root(int i, float &cube_root) -- as above
Whether the number is even or odd
bool even_or_odd(int i) which returns true if the value is even and false otherwise.
Whether the number is prime or not (Prepare a user-defined function based on the logic in Assignment 5)
bool prime(int i) which returns true if the value is prime. (use assignment 5).
Save the results of the calculations in a set of arrays, one array for each calculated value.
for each result store it in an array (square_root_array, cube_root_array, etc.)
After all values are calculated and saved, display the values in a tabular form with one column for each calculated value and a row for each set of values (corresponding to the first value read from the user).
call a function void display_values(float square_root_array[], ...) which iterates through each of your arrays and prints the values according to the rules listed below:
Note that for each negative value in the first column, display “N/A” in the columns for square root and cube root.
Display “Even” or “Odd” for each number’s even/odd status.
Display “True” or “False” for the number’s prime-ness.
The next part is already handled by our while loop.
Repeat this process until the user enters a count of zero for the number of values in the table.
I will leave the Bonus for you to figure out.
Bonus: Read a series of three-number sets from a data file named triples.txt and create a table of numbers corresponding to each three-number set. Save the resulting tables of numbers to a single text file named numbers.csv in comma-separated-value format.
Good luck, and get used to working all nighters if you plan on taking a lot of CS. It's par for the course.
P.S. If you follow these directions and look up how to do each step where you are unsure, you could get this project off of your plate in a couple hours.

Creating a histogram with C++ (Homework)

In my c++ class, we got assigned pairs. Normally I can come up with an effective algorithm quite easily, this time I cannot figure out how to do this to save my life.
What I am looking for is someone to explain an algorithm (or just give me tips on what would work) in order to get this done. I'm still at the planning stage and want to get this code done on my own in order to learn. I just need a little help to get there.
We have to create histograms based on a 4 or 5 integer input. It is supposed to look something like this:
Calling histo(5, 4, 6, 2) should produce output that appears like:
*
* *
* * *
* * *
* * * *
* * * *
-------
A B C D
The formatting to this is just killing me. What makes it worse is that we cannot use any type of arrays or "advanced" sorting systems using other libraries.
At first I thought I could arrange the values from highest to lowest order. But then I realized I did not know how to do this without using the sort function and I was not sure how to go on from there.
Kudos for anyone who could help me get started on this assignment. :)
Try something along the lines of this:
Determine the largest number in the histogram
Using a loop like this to construct the histogram:
for(int i = largest; i >= 1; i--)
Inside the body of the loop, do steps 3 to 5 inclusive
If i <= value_of_column_a then print a *, otherwise print a space
Repeat step 3 for each column (or write a loop...)
Print a newline character
Print the horizontal line using -
Print the column labels
Maybe i'm mistaken on your q, but if you know how many items are in each column, it should be pretty easy to print them like your example:
Step 1: Find the Max of the numbers, store in variable, assign to column.
Step 2: Print spaces until you get to column with the max. Print star. Print remaining stars / spaces. Add a \n character.
Step 3: Find next max. Print stars in columns where the max is >= the max, otherwise print a space. Add newline. at end.
Step 4: Repeat step 3 (until stop condition below)
when you've printed the # of stars equal to the largest max, you've printed all of them.
Step 5: add the -------- line, and a \n
Step 6: add row headers and a \n
If I understood the problem correctly I think the problem can be solved like this:
a= <array of the numbers entered>
T=<number of numbers entered> = length(a) //This variable is used to
//determine if we have finished
//and it will change its value
Alph={A,B,C,D,E,F,G,..., Z} //A constant array containing the alphabet
//We will use it to print the bottom row
for (i=1 to T) {print Alph[i]+" "}; //Prints the letters (plus space),
//one for each number entered
for (i=1 to T) {print "--"}; //Prints the two dashes per letter above
//the letters, one for each
while (T!=0) do {
for (i=1 to N) do {
if (a[i]>0) {print "*"; a[i]--;} else {print " "; T--;};
};
if (T!=0) {T=N};
}
What this does is, for each non-zero entered number, it will print a * and then decrease the number entered. When one of the numbers becomes zero it stops putting *s for its column. When all numbers have become zero (notice that this will occur when the value of T comes out of the for as zero. This is what the variable T is for) then it stops.
I think the problem wasn't really about histograms. Notice it also doesn't require sorting or even knowing the