I'm having trouble storing real time data in an array.
I have a 1D array that reads data in real time, this is fine and it's printing me data like this:
D/this is my array: arr: = [-1.43, -3.5916, 2.71, 4.42, -4.4, 0.0]
This data represents ONE sample, and I'm reading data 1000 samples per second, so if I print this array, it shows me reading per reading, I mean 1000 arrays like the picture (with different data) per second.
Now, I need to process that data, so I need to store the first 256 samples in a 2D array, process that array and then get a new one with the next 256 samples and so on.. But I haven't been able to do this.
transformed if my 1D array that shows me sample by sample. And buff is the matrix I want to store the data into.
This is how I get transformed, it is first short[] and then I'm converting it to double:
short[] yaxis = msg.getData().getShortArray(BiopluxService.KEY_FRAME_DATA);
double[] transformed = new double[yaxis.length];
for (int j = 0; j < yaxis.length; j++) {
transformed[j] = (double) yaxis[j];
}
This is what I have so far:
double[][] buff = new double[256][6];
for (int f = 0; f < 256; f++) {
buff[f] = transformed;
}
Log.d("this is my array", "arr: " + Arrays.deepToString(buff));
But my buff array has the same values.
Why doesn't the array contain different values
You are setting all the rows to point to the same array, if you run this code:
public class ClassNameHere {
public static void main(String[] args) {
double[][] d = new double[5][];
double[] row = {1,2,3};
for (int i = 0; i < 5; i++) {
d[i] = row;
}
}
}
Through this tool, you can see that at the end of this code all of the rows point to the exact same array, so they will all be equal.
How to fix
You want to create a new array for transformed each time, and then load into that array, so all the rows are different arrays, allowing them to have different values.
Related
I'm trying to make a static 2D array object. I came up with one where it has to be initialized by the user but for my purposes I want it to be already initialized.
String str;
int temp = 0;
int check = 0;
Plot[][] farm = new Plot[4][3];
ExperimentalFarm p = new ExperimentalFarm(farm);
for (int i = 0; i < farm.length; i++) {
for (int j = 0; j < farm[i].length; j++) {
str = JOptionPane.showInputDialog("Name the crop");
temp = Integer.parseInt(JOptionPane.showInputDialog("What is the yield"));
farm[i][j] = new Plot(str, temp);
}
}
I'm also trying to return an object from a class to the client. For example, I want to get which player did the best. I want to have their name and their score. How do I return that.
Well, you're doing it. Plot[][] farm = new Plot[4][3]; makes a new 2D array (technically, java does not have 2D arrays. At all. What you can do, however, is a 1D array, whose elements are themselves arrays, which is exactly what that does: farm is of type: "An array whose component types are arrays whose component types are Plot objects", and new Plot[4][3] initializes this array to contain 3 sub-arrays, and each sub-array is initialized to contain an array capable of holding 4 plots.
But that just makes room for plots, it doesn't instantiate 12 plot objects, you have to do that yourself. You are doing just that in the code you pasted: That loop structure ends up running the stuff within ("Name the crop", etc) a grand total of 12 times, meaning, new Plot is executed 12 times, you want that to happen.
Here's how to e.g. do it yourself:
Plot[][] farm = new Plot[4][3];
for (int i = 0; i < farm.length; i++) {
for (int j = 0; j < farm[i].length; j++) {
farm[i][j] = new Plot("barren", 0);
}
}
I have a method which is intended to slice one bigger Array into a few smaller arrays. I would like it to return these arrays as an two dimensional array. So far slicing works but I have no idea how to write arr2[] elements to slice[][]. The problem is count of arrays slice[?][i] is unknown.
private short[][] slice(short array1[], int sliceSize) {
short arr2[]=null;
short slice[][]=null;
for (int offset = 0; offset < array1.length ; offset+=sliceSize) {
arr2 = Arrays.copyOfRange(array1, offset, offset+sliceSize);
for(int i=0; i<arr2.length; i++) {
System.out.print("\n value: "+ String.valueOf(arr2[i]));
// slice[?][i]=arr2[i];
}
}
return slice;
}
You can easily know the number of slice you need from the orignal array length.
int sliceCount = arr1.length / sliceSize + 1;
short[][] slice = new short[sliceCount][];
Note that we would end up with one to many cell if the length is a multiple of the slice size, we can simply substract 1 to arr1.length to correct that (didn't do it to keep the code simple)
Then, you just need to do some copy just like you do and store the result in it.
Since Arrays.copyOfRange return a new array instance each call, you can store the instance directly instead of iterating the array.
for (int i = 0; i < sliceCount; i++) {
arr2 = Arrays.copyOfRange(array1, i * sliceSize, ( i + 1 ) * sliceSize);
slice[i] = arr2;
}
return slice;
Example :
[1,2,3,4,5,6,7,8,9] into slice of 4 length
-> [
[1,2,3,4],
[5,6,7,8],
[9,0,0,0]
]
So I'm trying to make an two dimensional ArrayList which has a set amount of ArrayLists, then each of those ArrayLists can contain as much as needed. I'm aware that arrays dynamically change size, but I'm trying to guarantee that is has at least a certain size in this case.
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>(10);
This doesn't work. I want to be able to set the location of a new Integer to one of the first dimension's indices, like so:
integers.get(7).add(new Integer(42));
This just gives me an IndexOutOfBoundsException, as though there are no Integer ArrayLists within the ArrayList. Is there a way to do this? I'm sure it's something simple I'm not seeing.
Array lists do not work like this. They are not arrays.
The list you created is backed by array of at least 10 elements, but itself it does not contain any, so you cannot refer to 7th or actually any one element.
integers.size() would return 0
integers.isEmpty() would return true
integers.get(0) would throw
Moreover, the list you initialized needs to be filled with lists themselves:
for (int i = 0; i < 10; ++i) {
row = new ArrayList<Integer>()
integers.add(row);
}
// now integers is a 10-element list of empty lists
Alternatively you could use primitive arrays (if you want to have a fixed-size rectangle).
int integers[][] = new int[10][];
for (int i = 0; i < integers.length; ++i) {
integers[i] = new int[10]; // rows are initialized to 0, as int is primitive
}
for (final int[] arr : integers) {
System.out.println(Arrays.toString(arr));
}
You can use a nested loop for this. Here is a short example:
import java.util.ArrayList;
public class PopulateArray {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>();
int num_arrays_ to_populate = 10;
int num_indices_to_populate = 10;
for(int i = 0; i < num_arrays_to_populate; i++) {
integers.add(new ArrayList<Integer>());
for(int j = 0; j < num_indices_to_populate; j++) {
integers.get(i).add(0);
}
}
}
}
This would create an ArrayList of ArrayLists of ints and fill the top ArrayList with 10 ArrayLists and put a 0 in the first 10 cells of each. Obviously you can change any of those numbers to do what you want.
Note/Disclaimer: I wrote this on my phone, so if I missed a brace or semicolon, just comment and I’ll add it. The logic is there, though.
I have a 2D array which consist of image pixels which its size depends on the size of the input image. I need to break it into smaller 9x9 arrays. To give a clearer picture, I try to illustrate the situation:
//The number of rows and columns of the smallerArray will look something like this:
It should copy them from the imagePixels array iterating through each 8 columns, then move on to the next 8 rows.
1st small 2nd small 3rd small and so on..
array: array: array:
012345678 91011121314151617 181920212223242526 ....
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
Then move on to next 8 rows:
012345678 91011121314151617 181920212223242526 ....
9 9 9
10 10 10
11 11 11
12 12 12
13 13 13
14 14 14
15 15 15
16 16 16
17 17 17
.
.
.
I have done the following code but could not get my logic right. How can I stop the iteration:
Copy up until the 9th column or row, store it in an array, resume copying on the 10th column/row, stop when it reaches 9 column/row after, store it in another array, and keep on doing that till it finishes copying the imagePixels array.
I tried to store the arrays in an ArrayList so it would be easier for me to manipulate and do calculation stuffs with all the smallerArrays.
ArrayList<double[][]> collectionofSmallArrays = new ArrayList();
double[][] imagePixels = new double[1600][1000]; //Lets say this is the size of the image
double[][] smallerArray = new double[9][9];
for(int a = 0; a<smallerArray.length; a++)
{
for(int b =0; b<smallerArray[a].length; b++)
{
for(int c=0; c<imagePixels.length; c++)
{
for(int d=0; d<imagePixels[c].length; d++)
{
smallerArray[a][b] = imagePixels[c][d];
...(code to stop the iteration if it reaches 9, store it in array then resume where it stops with another new array)
collectionofSmallArrays.add(smallerArray);
}
}
}
}
Can anyone work around the code to achieve the expected result? Appreciate it.
You should probably provide more context information. Saying that an array of double values represents pixels sounds dubios. If you are working with images, then you might find solutions on a completely different level of abstraction (I'm thinking about BufferedImage#createSubImage here).
However, to answer the question: You should break the task up into smaller parts. Particularly, it might be easier to implement two methods:
One method that receives an input array, some coordinates, and an output array, and that copies the data from the specified coordinates of the input array to the output array
One method that calls the above mentioned method with the appropriate coordinates to split the whole array into the parts of the desired size.
In pseudocode:
for (each coordinates (9*r,9*c)) {
copy the rectange (9*r,9*c)-(9*r+9,9*c+9) of the input array into an array
A very simple implementation/test is shown in the following example. Note that this could be generalized and improved, but I think it shows the basic idea:
import java.util.ArrayList;
import java.util.List;
public class SubArrayTest
{
public static void main(String[] args)
{
double inputArray[][] = createInputArray(160, 100);
System.out.println("inputArray: "+toString(inputArray));
List<double[][]> subArrays = createSubArrays(inputArray, 9, 9);
for (double subArray[][] : subArrays)
{
System.out.println("subArray:\n"+toString(subArray));
}
}
private static List<double[][]> createSubArrays(
double inputArray[][], int subRows, int subCols)
{
List<double[][]> subArrays = new ArrayList<double[][]>();
for (int r=0; r<inputArray.length; r+=subRows)
{
for (int c=0; c<inputArray[r].length; c+=subCols)
{
double subArray[][] = new double[subRows][subCols];
fillSubArray(inputArray, r, c, subArray);
subArrays.add(subArray);
}
}
return subArrays;
}
private static void fillSubArray(
double[][] inputArray, int r0, int c0, double subArray[][])
{
for (int r=0; r<subArray.length; r++)
{
for (int c=0; c<subArray[r].length; c++)
{
int ir = r0 + r;
int ic = c0 + c;
if (ir < inputArray.length &&
ic < inputArray[ir].length)
{
subArray[r][c] = inputArray[ir][ic];
}
}
}
}
//===Test methods=========================================================
private static double[][] createInputArray(int rows, int cols)
{
double array[][] = new double[rows][cols];
for (int r=0; r<array.length; r++)
{
for (int c=0; c<array[r].length; c++)
{
array[r][c] = r*100+c;
}
}
return array;
}
private static String toString(double array[][])
{
String format = "%7.1f";
StringBuilder sb = new StringBuilder();
for (int r=0; r<array.length; r++)
{
for (int c=0; c<array[r].length; c++)
{
sb.append(String.format(format, array[r][c])+" ");
}
sb.append("\n");
}
return sb.toString();
}
}
Side notes:
You should always declare variables with their interface type. This means that you should not write
ArrayList<String> x = new ArrayList<String>();
but always
List<String> x = new ArrayList<String>();
In the posted code, you seemed to always add the same instance of the sub-array to the list. This means that in the end you would have many instances of the same array in the list, all with the same content. Somewhere in between you have to create a new double[9][9] array.
smallerArray[a][b] = imagePixels[c][d] line looks strange. You reuse same array instance. Your output array list will contain multiple reference to same array.
You cannot reuse smallerArray. Create the instance inside the for loop and store the size in a constant.
I think a map with some corner coordinates as a key would be far better than a list for storing your results.
What happens if the length or width or your image is not divisible by 9?
I'm having difficulty understand how to write this array. I need it to out-print 10x5 (50 elements total), and have the first 25 elements equal to the sqrt of the index that it is in, and the last 25 to equal 3 * the index. Yes, this is homework but I'm not asking for you to do it for me, I just need help! I'm getting errors when using Math saying that I cant use double and the double array together. Here is what I have so far:
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double[10][5];
double[] sum, sum2;
for (int count=0; count<=25;count++) {
alpha[count]= Math.sqrt(count);
}
for (int count=26; count<=50;count++) {
alpha[count]= count *3;
}
for (int count=0; count<=50;count++) {
System.out.print(alpha[count]);
}
}
}
Because alpha is a multidimensional array, you can't refer to its elements like a normal array.
int myarray[][] = new int[2][2];
In the above example, the array myarray is multidimensional. If I wanted to access the second element in the first array, I would access it like this:
int myint = myarray[0][1];
You are trying to access a multidimensional array by using the access for a normal array. Change
alpha[count]
to
alpha[0][count]
or similar.
Read here for more information on multidimensional arrays.
you defined alpha as a 2D array with lets say 10 items in the first dimension and 5 in the second, and 5x10 is 50 elements.
When using your array to assign values to these elements, u must call upon the array using 2 indices, one for each dimension:
alpha[i][j] = /*double value*/; //with 0<=i<=9 and 0<=j<=4
So the first 25 elements going from left to right in dimension order is going to be:
[0to9][0] and [0to9][1] and [0to4][2]
the next 25 will be
[4to9][2] and [0to9][3] and [0to9][4]
from then on i cannot give you the answers to your homework, but the loops should look like this:
int j;
for(int i = 0; i<25; i++)
{
j=i/10; //integer division will return 0 for i<10, 1 for 10<i<20, etc..
alpha[i%10][j] = Math.sqrt(i);
}
and you can figure out the rest
The 10x5 appears to be an output constraint, not a design constraint.
You are using Java, so use Java constructs, not C-language constructs;
specifically store the values in a List not an array.
Here are some hints:
List<Integer> valuesList = new ArrayList<Integer>();
for (int index = 0; index < 25; ++index)
Integer currentValue = Math.sqrt(index);
valuesList.add(currentValue);
for (int index = 25; index < 50; ++index)
Integer currentValue = index * 3;
valuesList.add(currentValue)
int count = 1;
for (Integer current : valuesList)
if ((count % 5) == 0) // write a newline.
System.out.print(current);
++count