In Java I would like to concatenate an array (a[], fixed length) to an array of the same length, to create a matrix M[2][length of a]. This way I would like to subsequently paste more of those arrays onto the matrix. (Comparable to the Matlab vertcat function..C=[A;B])
Is this possible?
Thanks
Yes, it is possible. Here is an example:
public class Main
{
public static void main(String[] args)
{
int[] A = new int[]{1, 2, 3};
int[] B = new int[]{4, 5, 6};
int[][] M = new int[2][];
M[0] = A;
M[1] = B;
for ( int i = 0; i < 2; i ++ ){
for (int j = 0; j < M[i].length; j++ ){
System.out.print(" "+ M[i][j]);
}
System.out.println("");
}
}
}
The above prints out:
1 2 3
4 5 6
We can do even better than that, though. If you are using Java 5 or higher, use:
public static int[][] vertcat(int[]... args){
return args;
}
Then you can write:
int[][] M = vertcat(A,B);
And it will work for any number of arguments.
Edit
The above method stuffs the original arrays into another array, which means that any modification to the result will affect the original arrays, which may be undesireable. Use the following to copy the values:
public static int[][] copyMatrix(int[][] original){
if ( (original==null) || (original.length==0) || (original[0].length == 0) ){
throw new IllegalArgumentException("Parameter must be non-null and non-empty");
}
rows = original.length;
cols = original[0].length;
int[][] cpy = new int[rows][cols];
for ( int row = 0; row < rows; row++ ){
System.arraycopy(original[row],0,cpy[row],0,cols);
}
return cpy;
}
If you want vertcat to return a copy rather than the original, you can redefine it as:
public static int[][] vertcat(int[]... args){
return copyMatrix(args);
}
As far as I know, Java has no built-in support for matrices and matrix-related operations. I would either use a 2D array, write my own Matrix wrapper class (in simpler cases) or hunt down a good Matrix library (e.g. http://jmathtools.berlios.de/).
Related
I'm new to java and am trying to find the transpose of a matrix X with m rows and x columns. I'm not familiar with java syntax but I think I can access the number of rows using double[x.length] but how do I figure out the number of columns? Here is my code:
import stdlib.StdArrayIO;
public class Transpose {
// Entry point
public static void main(String[] args) {
double[][] x = StdArrayIO.readDouble2D();
StdArrayIO.print(transpose(x));
}
// Returns a new matrix that is the transpose of x.
private static double[][] transpose(double[][] x) {
// Create a new 2D matrix t (for transpose) with dimensions n x m, where m x n are the
// dimensions of x.
double[][] t = new double[x.length][x[1.length]]
// For each 0 <= i < m and 0 <= j < n, set t[j][i] to x[i][j].
// Return t.
}
}
Also, I was trying to figure it out by printing a 2D list in a scrap file but It wouldn't work for some reason, where is what I had:
import stdlib.StdArrayIO;
import stdlib.StdOut;
public class scrap {
public static void main(String[] args){
double[][] x = new double[10][20];
StdOut.println(x.length);
}
}
Could you point out what I was doing wrong? It kept waiting on input. I could also use any other tips that would help, I am transitioning from Python.
In Java, a two-dimensional array is merely an array of arrays. This means the length of any of the array elements can be checked to find the number of columns. Using your example, this would be:
double[][] t = new double[x[0].length][x.length];
This should be sufficient for your matrix situation, where we can assume the outer array is not empty, and all inner arrays have the same length.
Note that this is not guaranteed to work in general. If the outer array is empty, there are no inner arrays to check, so the number of columns isn't defined and can't be determined. Secondly, there is no guarantee that all inner arrays of a given array of arrays in Java are all the same length. They will be using the new double[x][y] syntax, but the array could have been created using another mechanism or one of the inner arrays could have been replaced with an array of a different length.
class TwoDmArray {
public static void main(String[] args) {
int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 } };
for(int i = 0; i < 2; i++) { // It represents row
for(int j = 0; j < 3; j++) { // It represents column
System.out.print(arr[i][j]);
if(j == 2) { // When column index will be 2 then will print elements in new line
System.out.println();
}
}
}
}
}
OUTPUT : 123
456
Explanation : Here array has 2 rows and 3 columns so, matrix will be in row and column form.
So this program starts by initializing two 2d arrays that are 4 by 4. the arrays are filled with random numbers between 9 and 0. I already did those methods, and they print correctly. then, i need to compare each number in those two using enhanced for loops ONLY. whichever one is bigger will print, creating a new array. I know how to do this with regular for loops, but how would do this? hopefully this makes sense. I don't even know where to start with this, honestly.
my instance variables are:
private int[][] matrix1 = new int[4][4]; //
private int[][] matrix2 = new int[4][4];
public static int[][] solve(int[][] matrix1, int[][] matrix2) {
// ignore matrix1 has same size with matrix2
int[][] res = new int[matrix1.length][matrix1[0].length];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
res[i][j] = Math.max(matrix1[i][j], matrix2[i][j]);
}
}
return res;
}
we have the repmat(arr,2,1,2) method in matlab produce a format which is :
arr = [6,3,9,0];
L(:,:,1) =
6 3 9 0
6 3 9 0
L(:,:,2) =
6 3 9 0
6 3 9 0
the java code that i tried to produce same format is
class test24{
public static void main ( String [] args ) {
int[] arr = {6,3,9,0};
test24 test = new test24();
System.out.println(Arrays.deepToString(test.repmat(arr,2,1,2)));
}
public static int[][][] repmat (int[] array, int rows, int columns, int depth)
{
int arrayColumns = array.length;
int resultColumns = arrayColumns * columns;
int[][][] result = new int[rows][resultColumns][depth];
int z = 0;
for (int d = 0; d < depth; d++)
{
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < resultColumns; c++)
{
result[r][c][d] = array[z++];
if (z >= arrayColumns)
{
z = 0;
}
}
}
}
return result;
}
}
the the result from the java code is :
[[6,6],[3,3],[9,9],[0,0]],[[[6,6],[3,3],[9,9],[0,0]]???
please any suggestion
I believe that the depth argument causes that each value within the array has two values (int[][][] result = new int[rows][resultColumns][depth]; would become (given the inputs rows=2, columns=1 and depth=2 and an initial array of 4) new int[2][1][2]).
Not entirely sure what the repmat method exactly should do put it might be that changing the creation of the array into int[][][] result = new int[depth][rows][resultColumns]; fixes the issue.
I imagine that this is because MATLAB used column-major indexing whereas Java uses Iliffe vectors. So MATLAB stores multidimensional vectors using a single contiguous block of memory where Java stores an array of pointers and each pointer points to another array.
It's difficult to tell exactly what the Java data-structure your code resulted in was. Do you think maybe you could rather post a screen shot from a debugger? What you have now does not look correct, the brackets don't even match.
At a guess though, I would suggest that you maybe change this line
result[r][c][d] = array[z++];
To something more like
result[d][r][c] = array[z++];
Or possibly to even alter the inner loop to something like
for (int c = 0; c < columns; c++) {
result[d][r][c] = array;
}
I have any amount of arrays of integers like:
[1,9]
[5]
[7]
And I want to combine them in such a way that I get sets of numbers like:
[1,5,7]
[9,5,7]
Another Example INPUT:
[1,9]
[3,5]
[7]
[10]
OUTPUT:
[1,3,7,10]
[9,3,7,10]
[1,5,7,10]
[9,5,7,10]
I have tried nesting "for" loops but I always seem to get lost and can't get the right iterators I need to pull the right numbers when building the final array. There can be any number of integers in each array, and any number of arrays.
I have tried something like this, but it seems like a deadend:
int[][] allIndexes = {{1, 9},{5},{7}};
List<Integer> dataset1 = new ArrayList<Integer>();
//int[] dataset2 = {};
int i = 0;
for (int[] indexSet : allIndexes){
if(indexSet.length > i){
dataset1.add(indexSet[i]);
}else{
dataset1.add(indexSet[0]);
}
i++;
}
System.out.println(dataset1.toString());
//System.out.println(dataset2);
Any help would be greatly appreciated. I tried searching for others, but I really am not sure if I am defining this correctly.
You need a variable number of nested loops to enumerate all cases. Thus, recursion is your friend here. The code below will do what you're asking.
public static void main(String[] args)
{
int[][] allIndexes = {{1, 9},{3,5},{7},{10}};
List<Integer> dataset1;
if( allIndexes.length > 0)
{
int[] firstIndexes = allIndexes[0];
for( int i = 0; i < firstIndexes.length; i++)
{
dataset1 = new ArrayList<Integer>();
dataset1.add( firstIndexes[i]);
foo( dataset1, allIndexes, 1);
}
}
}
public static void foo( List<Integer> dataset1, int[][] allIndexes, int index)
{
if( index < allIndexes.length)
{
int[] indexes = allIndexes[index];
for( int i = 0; i < indexes.length; i++)
{
List<Integer> dataset = new ArrayList<Integer>();
for( Integer integer : dataset1)
dataset.add( integer);
dataset.add( indexes[i]);
foo( dataset, allIndexes, index+1);
}
}
else
{
StringBuilder sb = new StringBuilder();
sb.append( "[");
for( int i = 0; i < dataset1.size() - 1; i++)
sb.append( dataset1.get( i) + ",");
sb.append( dataset1.get( dataset1.size()-1));
sb.append( "]");
System.out.println( sb.toString());
}
}
Edit seems uoyilmaz was faster with his answer
Edit2 fixed a typo
I think a recursive approach might be worth a try.
You have your first input array and all following input arrays.
You want to get all combinations of your following input arrays and combine each of them with every element from your first input array
[1,9] // first input array
[5] // following input arrays
[7] // following input arrays
.
void GetCombinations(int[][] arrays, int startIndex, LinkedList<LinkedList<Integer>> outLists) {
// startIndex to high
if (startIndex >= arrays.length) return;
int[] firstArray = arrays[startIndex]
LinkedList<LinkedList<Integer>> subLists = new LinkedList<LinkedList<Integer>>();
// get sub-results
GetCombinations(arrays, startIndex + 1, subLists);
// combine with firstArray
if (subLists.size() == 0) {
subLists.add(new LinkedList<Integer>());
}
for (int i = 0; i < subLists.size(); ++i) {
for (int j = 0; j < firstArray.length; ++j) {
LinkedList<Integer> temp = new LinkedList<Integer>(subLists.get(i));
temp.addFirst(firstArray[j]);
outLists.add(temp);
}
}
}
You then call the function with
int[][] yourInputArrays = { ... };
LinkedList<LinkedList<Integer>> outputLists = new LinkedList<LinkedList<Integer>>();
GetCombinations(yourInputArrays, 0, outputLists);
If you are new to programming, the recursive approach might not be intuitive at first, but it is definitely worth looking into it.
I have looked around Stack Overflow and did some work myself with this code but doesn't matter whatever I do the answer prints to false but it has to print to true, also how can I Plot their running times as a function of their input size as scatter plots and then choose representative values of the size n, and run at least 5 tests for each size value n in the tests?
PrefixAverages1
import java.util.Arrays;
public class PrefixAverages1 {
static double array[] = new double[10];
public static void prefixAverages(){
for (int i = 0; i < 10; i++){
double s = array[i];
for (int j = 0; j < 10; j++){
s = s + array[j];
}
array[i] = s / (i + 1);
System.out.println(Arrays.toString(array));
}
}
public static double[] prefixAverages(double[] inArray) {
double[] outArray = new double[inArray.length];
return outArray;
}
public static void main(String... args) {
System.out.println(
Arrays.equals(
prefixAverages(new double[] {5, 6, 7, 8}),
new double[] {2, 2.5, 3.5, 4}
)
);
}
}
PrefixAverages2
import java.util.Arrays;
public class PrefixAverages2 {
static double array[] = new double[10];
public static void prefixAverages(){
double s = 0;
for (int i = 0; i < 10; i++){
s = s + array[i];
array[i] = s / (i + 1);
}
array[0] = 10;
System.out.println(Arrays.toString(array));
}
public static double[] prefixAverages(double[] inArray) {
double[] outArray = new double[inArray.length];
return outArray;
}
public static void main(String... args) {
System.out.println(
Arrays.equals(
prefixAverages(new double[] {3, 4, 5, 6}),
new double[] {2, 3.5, 4, 5}
)
);
}
}
First you must understand what Arrays.equals() method does. The Arrays.equals() method does comparison operation on two arrays, based on their content; not based on their size. First of all, let's look at your prefixAverages(float [] inArray) method. What you did there is just create a new float array of size equals to the size of the passing array, and then return that newly created array. And in the main method, you are comparing the returning array and a new array that you are supplying. But this is logically not correct. Since the returning array is an empty array; the Arrays.equals() method returns false, as the other array has some values in it. Even if the returning array do have some values, the Arrays.equals() method returns false if both contain different values. Always remember two arrays are equal if and only if they contain same values and the elements should be in the same order. ** Modify your program like this and it'll return **true
import java.util.Arrays;
public class PrefixAverages1 {
static double array[] = new double[10];
public static void prefixAverages(){
for (int i = 0; i < array.length; i++){
double s = array[i];
for (int j = 0; j < array.length; j++){
s = s + array[j];
}
array[i] = s / (i + 1);
System.out.println(Arrays.toString(array));
}
}
public static double[] prefixAverages(double[] inArray) {
double [] outArray = inArray;
return outArray;
}
public static void main(String... args) {
System.out.println(
Arrays.equals(
prefixAverages(new double[] {5, 6, 7, 8}),
new double[] {5, 6, 7,8}
)
);
}
}
One more thing. While using arrays in loop; always use array.length method to do comparison condition checking. Otherwise there is a high change of probability for an ArrayOutOfBoundsException condition.
I'm guessing because it's hard to understand what you are trying to do. But right now I'm not even sure how this code compiles, because you haven't defined any constructors, and you are (apparently attempting to) call a constructor (with the same name of a static class function, confusing AND bad form) with an array parameter. I'm guessing you meant to call the static method that takes a double[] parameter. (Right now, and here's the confusing part, it shouldn't compile because you should have to prefix the class name to call a static function.). Even that would fail, though, because that method returns an empty array of the same length of the input array. To top it all off, the "algorithm" section of your code is never even called.
I'd suggest just stepping through this in a debugger. That way you could see what the code is doing in real time and correct it if it's not what you meant.
Also, if you'd followed normal coding conventions (never name a function after the class; only constructors), it would be easier to spot errors like that.
Edit: I see how it compiles now. Still, naming the function after the class makes me think "constructor", along with everyone else on the planet.
The output you expect is incorrect; for the input 5, 6, 7, 8 the prefix average should be 5.0, 5.5, 6.0, 6.5.
After the first value 5, there has been one value (5). After the second value (6 + 5) there have been two values 11 (and 11 / 2 is 5.5). Then 6 (because 6+5+7 is 18) and 18/3 is 6. Finally 18+8 is 26 and 26/4 is 6.5
static double[] prefixAverages(double[] x) {
int len = x.length;
double[] arr = new double[len];
double sum = 0;
for (int i = 0; i < len; i++) {
sum += x[i];
arr[i] = sum / (i + 1);
}
System.out.println(Arrays.toString(arr));
return arr;
}