I have two sets of variables called ITEM 1 to ITEM 47, and another called L1 to L47. What I want to do is to calculate the sum of Ls if any ITEM#i=1. What I wrote is as following:
COMPUTE LSUM=0.
LOOP
#i=1 to 47.
IF (ITEM(#i)=1) LSUM=LSUM+L(#i).
END LOOP.
But I got an error message saying the characters do not match any existing function or vector. What should I do then? Your inputs will be very appreciated.
Thanks.
Sincerely,
Lucy
COMPUTE LSUM=0.
exe.
vector vitems = ITEM 1 to ITEM 47.
vector vl = L1 to L47.
LOOP #vecid = 1 to 47.
do IF ( vitems(#vecid) eq 1 and not missing(vl(#vecid)) ).
compute LSUM=LSUM+vl(#vecid).
end if.
END LOOP.
exe.
See the VECTOR command in SPSS. You can not just create loop and treat variables as in array. They must first be put into vectors. Also, check the COMPUTE command. I think SUM would be more appropriate because if you write " compute v1 = v2 + v3 " and v2 has data but v3 is blank, v1 will be blank.
Related
I'm starting with Python and I have a basic question with "for" loop
I have two array which contains a values of a same variables:
A = data_lac[:,0]
In the first array, I have values of area and in the second on, values of mean depth.
I would like to find a way to automatize my calculation with different value of a parameter. The equation is the following one:
g= (np.sqrt(A/pi))/n
Here I can calculte my "g" for each row. Now I want to have a loop with differents values of "n". I did this:
i=0
while i <= len(A)-1:
for n in range(2,6):
g[i] = (np.sqrt(A[i]/pi))/n
i += 1
break
In this case, I just have one column with the calculation for n = 2 but not the following one. I tried to add a second dimension to my array but I have an error message saying that I have too many indices for array.
In other, I would like this array:
g[len(A),5]
g has 5 columns each one calculating with a different "n"
Any tips would be very helpful,
Thanks
Update of the code:
data_lac=np.zeros((106,7))
data_lac[:,0:2]=np.loadtxt("/home...", delimiter=';', skiprows=1, usecols=(0,1))
data_lac[:,1]=data_lac[:,1]*0.001
#Initialisation
A = data_lac[:,0]
#example for A with 4 elements
A=[2.1, 32.0, 4.6, 25]
g = np.zeros((len(A),))
I believe you share the indexes within both loops. You were increasing the i (index for the upper while loop) inside the inner for loop (which index with n).
I guess you have A (1 dim array) and you want to produce G (2 dim array) with size of (Len(A, 5))
I am not sure I'm fully understand your require output but I believe you want something like:
i=0
while i <= len(A)-1:
for n in range(2,6):
g[i][n-2] = (np.sqrt(A[i]/pi))/n # n-2 is to get first index as 0 and last as 4
i += 1 # notice the increace of the i is for the upper while loop
break
Important - remember that in python indentation means a lot -> so make sure the i +=1 is under the while scope and not indent to be inside the for loop
Notice - G definition should be as:
g = np.zeros((len(A),4), dtype=float)
The way you define it (without the 4) cause it to be 1 dim array and not 2-dim
Did a test for class.. and they provided a sample test. One of the questions gave the following code which calculates the average of the items in a list , they then asked us to find all the errors:
# brightness levels –maximum is 100
shape_brightness = [15,92,38,42]
item_no = 0
total = 0
if (item_no < len(shape_brightness):
total = shape_brightness[item_no]
item_no = item_no + 1
average = total / item_no
print(“The average brightness level is “+str(averge))
However, in the solution they said the biggest error was that it should actually be a while statement .. and i dont understand why? Any explanation as to why??
You need to iterate over all elements to calculate the average. The if statement only visits the first element in this array.
When your code accesses shape_brightness[item_no], item_no is the index, so as it is 0, shape_brightness[item_no] is just the number 15. In order to include all the other values of shape_brightness in your average calculation, you want to access them as well, so to do that you increase your index item_no as many times as the number of elements you want to access by using a loop.
A while loop would be one way of iterating over all elements, and changing the 'if' to 'while' would be the fastest correction to this code, but a for loop, with additional changes, would also work. E.g.
for item in range(len(shape_brightness)):
execute
in which case the item_no counter becomes unnecessary.
Simple:
Because you need to iterate an array. That tranlates: you need some form of looping!
And if statement does not have that repetitive part required here!
You need to use a while loop because for calculating the sum and number of values for average. You need to repetitively add the values of shape brightness until you have added all the values. Currently, you are using an if block which is considering only first value of shape_brightness array. You need to put
total = shape_brightness[item_no]
item_no = item_no + 1
inside while loop
while(item_no < len(shape_brightness))
I want to create an array that can store the outputs each time that doing a loop. I think the problem is because in a every new iteration the numbers starts counting from the beginning so it stores only the last iteration! In each iteration the output is an array(7x3) so in total I have to have (28,3).But I tried a lot and i AM GETTING AN ARRAY (28,3) all with zeros except the last 7 rows.
Thank you very much
You can see the code below:
for t=1:ncell % in my case I have 4 cells
ti=sort(T,2)
tt= sort(Cell{t}.ExBot,2)
tq= sort(Cell{t}.ExTop,2)
te= sort(Cell{t}.ExBT,2)
%k=0
z=0
cc=[]
%%%%% for exbottom
I=ones(size(ti,1),1);
for j=1:size(tt,1)
for i=1:size(ti,1)
if tt(j,:)==ti(i,:)
k=k+1 ;
%c(k,:)=[ti(j,:), ti(j+1,:)]
I(i)=0;
cc(k,:)=Y(i,:);
cc(size(tt,1)+1,:)=cc(1,:)
else
end
end
end
end
Although more info would help as mentioned in the comments, from the information you've given, the problem is most likely in setting cc to empty when you start processing each cell.
cc=[];
On exiting the outermost loop you will only have results for the last iteration.
On a related note you may want to use isequal or all for the comparison of vectors i.e. if isequal(tt(j,:),ti(i,:))
I have 26 variables and each of them contain numbers ranging from 1 to 61. I want for each case of 1, each case of 2 etc. the number 1 in a new variable. If there is no 1, the variable should contain 2.
So 26 variables with data like:
1 15 28 39 46 1 12 etc.
And I want 61 variables with:
1 2 1 2 2 1 etc.
I have been reading about creating vectors, loops, do if's etc but I can't find the right way to code it. What I have done is just creating 61 variables and writing
do if V1=1 or V2=1 or (etc until V26).
recode newV1=1.
end if.
exe.
**repeat this for all 61 variables.
recode newV1 to newV61(missing=2).
So this is a lot of code and quite a detour from what I imagine it could be.
Anyone who can help me out with this one? Your help is much appreciated!
noumenal is correct, you could do it with two loops. Another way though is to access the VECTOR using the original value though, writing that as 1, and setting all other values to zero.
To illustrate, first I make some fake data (with 4 original variables instead of 26) named X1 to X4.
*Fake Data.
SET SEED 10.
INPUT PROGRAM.
LOOP Id = 1 TO 20.
END CASE.
END LOOP.
END FILE.
END INPUT PROGRAM.
VECTOR X(4,F2.0).
LOOP #i = 1 TO 4.
COMPUTE X(#i) = TRUNC(RV.UNIFORM(1,62)).
END LOOP.
EXECUTE.
Now what this code does is create four vector sets to go along with each variable, then uses DO REPEAT to actually refer to the VECTOR stub. Then finishes up with RECODE - if it is missing it should be coded a 2.
VECTOR V1_ V2_ V3_ V4_ (61,F1.0).
DO REPEAT orig = X1 TO X4 /V = V1_ V2_ V3_ V4_.
COMPUTE V(orig) = 1.
END REPEAT.
RECODE V1_1 TO V4_61 (SYSMIS = 2).
It is a little painful, as for the original VECTOR command you need to write out all of the stubs, but then you can copy-paste that into the DO REPEAT subcommand (or make a macro to do it for you).
For a more simple illustration, if we have our original variable, say A, that can take on integer values from 1 to 61, and we want to expand to our 61 dummy variables, we would then make a vector and then access the location in that vector.
VECTOR DummyVec(61,F1.0).
COMPUTE DummyVec(A) = 1.
For a record if A = 10, then here DummyVec10 will equal 1, and all the others DummyVec variables will still by system missing by default. No need to use DO IF for 61 values.
The rest of the code is just extra to do it in one swoop for multiple original variables.
This should do it:
do repeat NewV=NewV1 to NewV61/vl=1 to 61.
compute NewV=any(vl,v1 to v26).
end repeat.
EXPLANATION:
This syntax will go through values 1 to 61, for each one checking whether any of the variables v1 to v26 has that value. If any of them do, the right NewV will receive the value of 1. If none of them do, the right NewV will receive the value of 0.
Just make sure v1 to v26 are consecutively ordered in the file. if not, then change to:
compute NewV=any(vl,v1, v2, v3, v4 ..... v26).
You need a nested loop: two loops - one outer and one inner.
There is one equation has 5 variable parameters. Each parameter has one for loop so this equation depends on the 5 for loops and i want to appear the results of this equation in matrix array. How can i do it?
for m1= 1:m1_end;
m1_vec=zeros(1,col_no/m1_end)+m1;
input_mat(1,col_no/m1_end*(m1-1)+1:col_no/m1_end*m1)= m1_vec;
for m2= 1:m2_end;
m2_vec=zeros(1,col_no/m2_end^2)+m2;
input_mat(2,col_no/m2_end^2*(m2-1)+1:col_no/m2_end^2*m2)= m2_vec;
for k1=1:k1_end;
k1_vec=zeros(1,col_no/k1_end^3)+k1;
input_mat(3,col_no/k1_end^3*(k1-1)+1:col_no/k1_end^3*k1)= k1_vec;
for k2=1:k2_end;
k2_vec=zeros(1,col_no/k2_end^4)+k2;
input_mat(4,col_no/k2_end^4*(k2-1)+1:col_no/k2_end^4*k2)= k2_vec;
for k3=1:k3_end;
input_mat(5,col_no/k3_end^5*(k3-1)+1:col_no/k3_end^5*k3)= k3;
M=[m1 0 ; 0 m2 ];
K=[k1+k2 -k2 ; -k2 k2+k3];
eigen_values=sqrt(eig(inv(M)*K))
end
end
end
end
end
How to show the all results of eigen_values in matrix ?
Your code is a bit messy, but you could start with something to hold all eigen_values
Either a matrix (if it is just a scalar) or a cell array if it is a vector.
Then each time after calculating eigen_values assign it to the correct place in your storage variable.
For example, if it is a scalar, and you track your progress with t:
all_eigen_values(t) = eigen_values;