Mean, variance and standard deviation in python - arrays

n,m = map(int,input().split())
A = []
for _ in range(n):
A.append(map(int,input().split()))
A = numpy.array(A)
print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))
Can anyone tell me what I am doing wrong?
I am getting error : numpy.AxisError: axis 1 is out of bounds for array of dimension 1
Also, I want the user to input the array of n x m dimensions.
How can I add the m dimension check ?
Please help.

When you are trying to append elements in the array, you are taking the elements using the map function, a map function will always return a map object and you are just appending map objects as elements to the array. So, when you are trying to access axis=1 actually there is no axis=1 present in the array because the array contains a single row with map objects.
Here is the correct code without using list comprehension,
n,m = map(int,input().split())
A = []
for _ in range(n):
A.append(list(map(int,input().split())))
A = numpy.array(A)
print(A)
print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))
Here is the code using list comprehension,
n,m = map(int,input().split())
A = []
for _ in range(n):
A.append([int(x) for x in input().split()])
A = numpy.array(A)
print(A)
print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))

Related

Why is mkString not working in Scala?

I can't get an array to print like a string normally in Scala
val a = Array("woot","yeah","ok then").sorted
for (i <- a.length-1 to 0 by -1)
println(s"$i: ${a(i)}")
val ab = ArrayBuffer(for (e <- a if e != null) yield e*3)
println(ab.mkString(" "))
For some reason, this prints:
2: yeah
1: woot
0: ok then
ArrayBuffer([Ljava.lang.String;#5034c75a)
And I was expecting it to print "yeahyeahyeah wootwootwoot ok thenok thenok then", that is, the items in the array (as strings) separated by a space. Why isn't it working and what am I doing wrong?
EDIT: ok, it was showing that because I was initializing ab to be a one-element ArrayBuffer with that array as the element instead of the elements of that inner array being separate elements of the array buffer.
If you want to print each element of the array, concatenated three times, with spaces between the entries, then it's just:
println((for (e <- a) yield e * 3).mkString(" "))
it gives:
ok thenok thenok then wootwootwoot yeahyeahyeah
(and this is the right order, because you wanted it sorted alphabetically, and o < w < y)
If you want to reverse the array before printing, you can initialize it to
val a = Array("woot","yeah","ok then").sorted.reverse
I think what you meant was
val ab = ArrayBuffer((for (e <- a if e != null) yield e*3): _*)
Some shorter answer using more functional approach:
val a = Array("woot","yeah","ok then").sorted.reverse
a.map(_ * 3).map(elem => print(elem + " ")
Edit:
If you want to have a result in some new variable you can do that:
val string = a.map(_ * 3).mkString(" ")

defining array from worksheet not working in filter () lines with type mismatch error

I'm using secondarray as range of cells in a worksheet (Ex. "1", "2") to exclude them as autofilter list that I'm defining in the below function in "filtercriteria".
I get "type mismatch" error in the filter (secondarray) line for some reason, but I works flawlessly when I define an array using a list of items instead. For example, if I use below line to define secondarray instead.
secondarray = ("1", "2")
I've researched similar postings and wasn't lucky, can someone help with this instance?
Thanks,
Dim secondArray As Variant
secondArray = Range("L76:M76").Value
c = 0
k = 0
count = 0
rowNumb = Worksheets("List").Range(Worksheets("List").Range("L5"), Worksheets("List").Range("L5").End(xlDown)).Rows.count
For L = 1 To rowNumb
c = Worksheets("List").Range("L5").Offset(L)
If c <> k Then
'check the current activity type against the array of types we don’t want. If it isn’t in the array we add it to an array that will be used as the filter criteria
If UBound(Filter(secondArray, c)) = -1 Then
ReDim Preserve filterCriteria(0 To count)
filterCriteria(count) = c
count = count + 1
End If
k = c
End If
Next
It isn't working because filter function takes a One-dimensional array of strings to be searched for its sourcearray argument.
When you read in a range from the sheet you automatically get a 2d array as opposed to the 1D you have when assigning from a list.
Find a way to use a 1D array to pass in
For example, as your data is coming from 1 row then slice the array by row
UBound(Filter(Application.WorksheetFunction.Index(secondArray, 1, 0), c)) = -1
You may need to find the right method for you.
Another method is given here.

Is there any way to create dynamic array in scala? Means inserting values at run time?

var arr=Array.ofDim[Int](4,4)
arr(0)(0)(0)(0)=12
this is one way to insert elements in array.
but if i need to initialize size of array dynamically or at run time. How can we do it in scala?
Here
val n = StdIn.readInt
val m = StdIn.readInt
val arr = Array.ofDim[Int](n, m)
arr(5)(15) = 1
println(arr.deep.mkString("\n"))
I created 2-dimensional array with sizes known only in runtime (I entered 10 and 20).
Or maybe you need scala.collection.mutable.ArrayBuffer if you're going to change sizes.
ArrayBuffer[Int] is 1-dimensional, ArrayBuffer[ArrayBuffer[Int]] is 2-dimensional etc.
val arr: ArrayBuffer[ArrayBuffer[Int]] =
ArrayBuffer.fill(10)(ArrayBuffer.fill(20)(0))
arr(5)(15) = 1
println(arr.mkString("\n"))
println
arr(5) += 1
arr += ArrayBuffer.fill[Int](25)(0)
println(arr.mkString("\n"))

How to extract different values/elements of matrix or array without repeating?

I have a vector/ or it could be array :
A = [1,2,3,4,5,1,2,3,4,5,1,2,3]
I want to extract existing different values/elements from this vector without repeating:
1,2,3,4,5
B= [1,2,3,4,5]
How can I extract it ?
I would appreciate for any help please
Try this,
A = [1,2,3,4,5,1,2,3,4,5,1,2,3]
y = unique(A)
B = unique(A) returns the same values as in a but with no repetitions. The resulting vector is sorted in ascending order. A can be a cell array of strings.
B = unique(A,'stable') does the same as above, but without sorting.
B = unique(A,'rows') returns the unique rows ofA`.
[B,i,j] = unique(...) also returns index vectors i and j such that B = A(i) and A = B(j) (or B = A(i,:) and A = B(j,:)).
Reference: http://cens.ioc.ee/local/man/matlab/techdoc/ref/unique.html
Documentation: https://uk.mathworks.com/help/matlab/ref/unique.html
The answers below are correct but if the user does not want to sort the data, you can use unique with the parameter stable
A = [1,2,3,4,5,1,2,3,4,5,1,2,3]
B = unique(A,'stable')

Sort array elements by the frequency of its elements

Is it possible in matlab/octave to use the sort function to sort an array based on the relative frequency of their elements?
For example the array
m= [4,4,4,10,10,10,4,4,5]
should result in this array:
[5,10,10,10,4,4,4,4,4]
5 is the less frequent element and is on the top while 4 is the most frequent and it's on bottom.
Should one use the indices provided by histcount?
The following code first calculates how often each element occurs and then uses runLengthDecode to expand the unique elements.
m = [4,4,4,10,10,10,4,4,5];
u_m = unique(m);
elem_count = histc(m,u_m);
[elem_count, idx] = sort(elem_count);
m_sorted = runLengthDecode(elem_count, u_m(idx));
The definition of runLengthDecode is copied from this answer:
For MATLAB R2015a+:
function V = runLengthDecode(runLengths, values)
if nargin<2
values = 1:numel(runLengths);
end
V = repelem(values, runLengths);
end
For versions before R2015a:
function V = runLengthDecode(runLengths, values)
%// Actual computation using column vectors
V = cumsum(accumarray(cumsum([1; runLengths(:)]), 1));
V = V(1:end-1);
%// In case of second argument
if nargin>1
V = reshape(values(V),[],1);
end
%// If original was a row vector, transpose
if size(runLengths,2)>1
V = V.'; %'
end
end
One way would be to use accumarray to find the count of each number (I suspect you can use histcounts(m,max(m))) but then you have to clear all the 0s).
m = [4,4,4,10,10,10,4,4,5];
[~,~,subs]=unique(m);
freq = accumarray(subs,subs,[],#numel);
[~,i2] = sort(freq(subs),'descend');
m(i2)
By combinging my approach with that of m.s. you can get a simpler solution:
m = [4,4,4,10,10,10,4,4,5];
[U,~,i1]=unique(m);
freq= histc(m,U);
[~,i2] = sort(freq(i1),'descend');
m(i2)
You could count the number of repetitions with bsxfun, sort that, and apply that sorting to m:
[~, ind] = sort(sum(bsxfun(#eq,m,m.')));
result = m(ind);

Resources