0

I've been working on a project where I needed to implement convolution and correlation methods using two formulas, which I did. Then I need to define the following method for printing f, correlation, and convolution side-by-side (which is the part I need help figuring out):

Convolution Formula:

(f * g)[n] = ∑ f[n + (M - 1) - m] * g[m]

where f is an array of size N, g is an array of size M, and f*g is the array of size N - M + 1 that stores the result of the convolution.

Correlation Formula:

(f ** g)[n] = ∑ f[n + m] * g[m]

where f is an array of size N, g is an array of size M, and f**g is the array of size N - M + 1 that stores the result of the correlation.

Define the following method for printing f, f*g, f**g side-by-side:

private static void print(double[] f, double[] convolution, double[] correlation)

This is what I have. Everything in main is driver code to test the program. I need help with the print method:

public static void main(String[] args) {
    double[] f = new double[18];
    for (int i = 0; i < f.length; i++) {
            f[i] = i;
    }
    double[] g1 = {0.25, 0.25, 0.5},
        g2 = {0.1, 0.2, 0.3, 0.4};

    print(f, convolution(f, g1), correlation(f, g1));
    print(f, convolution(f, g2), correlation(f, g2));

    for (int i = 0; i < f.length; i++) {
            f[i] = Math.sin(i);
    }

    print(f, convolution (f, g1), correlation(f, g1));
    print(f, convolution (f, g2), correlation(f, g2));
}

**private static void print(double[] f, double[] convolution, double[] correlation) {
    System.out.println("i\tf(i)\tconvolution[i]\tcorrelation[i]");

        for (int i = 0; i < convolution.length; i++) {
            System.out.println(i + "\t" + (f[i]) + "\t" + (convolution[i]) + "\t" 
                    + correlation[i] + "\t");

        }
            }**

private static double[] convolution (double[] f, double[] g) {
    int n = f.length - g.length + 1;                //N - M + 1
    double[] result2 = new double[n];           //create new array and define bounds

    for (int i = 0; i < n; ++i) {               //outer loop executes n times
        for (int j = 0; j < g.length; ++j) {        //inner loop executes up to the length of g
            result2[i] += f[i + (g.length - 1) - j] * g[j]; //convolution calculation
        }
    }
    return result2;

}
private static double[] correlation (double[] f, double[] g) {
    int n = f.length - g.length + 1;               // N - M + 1
    double[] result = new double[n];              // create new array and define bounds 

    for (int i = 0; i < n; ++i) {                // outer loop executes n times
        for (int j = 0; j < g.length; ++j) {    //inner loop executes up to the length of g
            result[i] += f[i + j] * g[j];      // correlation calculation
        }
    }

    return result;
}

}

This is an example of what the output should look like. This is the last printing as per the calls in the main method. I didn't want to include too much info: enter image description here

This is what I'm getting. I'm not really concerned about the formatting. enter image description here

I can't seem to get i to print 17 times and I'm unsure as to how to get it to print "----" for the empty values. Do I use an if statement? If I change the for loop in the print method to this:

for (int i = 0; i < f.length; i++) {
            System.out.println(i + "\t" + (f[i]) + "\t" + (convolution[i]) + "\t" 
                    + correlation[i] + "\t");

2 Answers 2

1

@panasconnie has the right concept (using printf() or the String.format() method) however I'm going to add my two cents worth anyways.

As you can see in the sample table, all the data is right aligned with the header and as you have stipulated there are some arrays that do not contain the same number of indexes (or elements) and are therefore replaced with "------". Converting the array elements to string (for display purposes only) allows us to easily do this. The conversion never affects any initial array data and therefore remains intact in its original state.

Because the f[] array is the array that contains the most elements it is that array that should be used for the iteration within your print() method. Whichever array contains the greatest amount indexes should be the array used for the iteration. The print() method sample I provide below will automatically determine which array is the largest and will use the length from that array within the for loop. This guarantees a full table display of data.

Keep in mind, there are several different ways to do this sort of thing in Java. I've opted to utilize both the String.format() method and the System.out.printf() method. You can see how both can work for you. They are basically the same.

The code below is over-commented of which can obviously be deleted if not required. It is only there for your initial benefit:

private static void print(double[] f, double[] convolution, double[] correlation) {
    // Determine which array contains the most elements.
    // We will use that array length for our iteration 
    // ahead.
    int maxArrayLenth = f.length;
    if (convolution.length > maxArrayLenth) { maxArrayLenth = convolution.length; }
    if (correlation.length > maxArrayLenth) { maxArrayLenth = correlation.length; }

    // Determine the location for the start of our header
    // so as to achieve proper right alignment. This means
    // it wont matter how many digits 'i' will contain, the 
    // table will always properly align.
    int hiVal = String.valueOf(f.length).length();

    // Print the Table Header to console...
    String header = String.format("%n%" + hiVal + "s %10s %15s %15s","i", "f(i)", 
                                  "convolution[i]", "correlation[i]");
    System.out.println(header);
    // Print the Table Header Underline to the exact length of our 
    // Table Header. We use the String.join() method in conjuction 
    // with the Collection Class nCopies() method so as to create 
    // a string of "=" characters. We subtract 2 from the header 
    // length because we used the String format's newline (%n) tag
    // to create a blank line before the Header itself for a cleaner
    // display of multiple tables.
    System.out.println(String.join("", Collections.nCopies(header.length() - 2, "=")));

    // Do the iteration through all the arrays using the length
    // based on our largest array.
    for (int i = 0; i < maxArrayLenth; i++) {
        // Convert the Double Data Type element from
        // each array into a String variable. This way
        // if any particular array does not contain a
        // designated index the string for that particular
        // array element will hold "------".
        String strgF; // current element from the f[] Array
        if (i > f.length-1) { strgF = "-------"; }
        // "%.5f" is used in format() to ensure a decimal precison of 5
        else { strgF = String.format("%.5f", f[i]); }

        String conv; // current element from the convolution[] Array
        if (i > convolution.length-1) { conv = "-------"; }
        else { conv = String.format("%.5f", convolution[i]); }

        String corr; // current element from the correlation[] Array
        if (i > correlation.length-1) { corr = "-------"; }
        else { corr = String.format("%.5f", correlation[i]); }

        // Print the current Table Data line...
        System.out.printf("%" + hiVal + "d %10s %15s %15s%n", i, strgF, conv, corr);
    }
}

EDIT: Based on OP's Comment(s):

Why Convert Double Type Array Elements To String:

You can of course use the printf() method to display double type (or float) data to console using the "%f" (or %e or %g) format tag (or otherwise known as the Conversion Type Character):

double num1 = 0.4975282369714;
double num2 = 3.3457546760063;
double num3 = -0.1761164402327;

System.out.printf("%.5f %10.5f %10.3f", num1, num2, num3);  

Would display to console something like: 0.49753 3.34575 -0.176

In essence, the printf() method (as does the String.format() method) actually converts the double to string and it sets the decimal precision automatically before displaying it. The problem here however is that if we want to actually display a string (like "-------") in place of a double data type value should that double be non-existent then we can't use the "%f" format tag, we need to use a different format tag (the "%s" format tag) otherwise we end up with a IllegalFormatConversionException. In this particular case, the easiest solution would be to pre-convert each double type value to a special String variable which is to represent that particular array value. If that value is non-existent (which in your case there are no elements to reach) then that variable would hold the String of "-------" instead of a string representation of a Double Type value. This does two things:

  1. It allows us to utilize one specific format tag (%s) within the printf() method so as to easily display the data in an organized fashion;
  2. It ensures that regardless of how many Indexes there may be between two, three, or more different arrays of particular Type values, each required value to display will contain something, either a string representation of a Type value or a simple string of dashes ("-------") depending upon the circumstances during the current iteration of those arrays.

You could of course code a means to build a custom format string for each iteration circumstance and along with each build an Object array to feed that format the required data, but trust me, this would be more runtime labour intensive than it's worth and it's harder to read later on down the road. Keep it simple, after all, it's only for display.

Read up on the System.out.printf() method.

1
  • @twobzombie - What part of "converting to string" are you confused about? Commented Jan 31, 2018 at 7:39
0

It looks like we are working on the same problem!

https://alvinalexander.com/programming/printf-format-cheat-sheet

http://www.oxfordmathcenter.com/drupal7/node/24

https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Have you looked into the printf method with java? You can format the answer with the print f method %.3f to include just three decimals.

Try

for (int i=0; i<convolution.length; i++) {
    System.out.printf("%f, %.3f, %.3f,%.3f", f[i],f[i], convolution[i], correlation[i]);
    System.out.println();

}

try something along the lines of that.

The way that I understand it is that the everything is listed in string format. The % marks what values need to be changed or affected by the formatting, they are then followed by characters that make its appearance different. Once you close the string you follow with a comma and list what values from the arrays are being placed or formatted in the table:

printf("%[flags][width][.precision]conversion-character", Values in array separated by the commas)

Please, Please, Please let me know if this has helped out! I am still learning too so there may be errors! Thanks

3
  • Hey thanks, but the problem is in printing all values of i up until 17, not the way that it is formatted.
    – twobzombie
    Commented Jan 31, 2018 at 6:11
  • Hmmm...Sorry about that @twobzombie. It seems I fell into the same trap about the formatting part within my answer. It's just that your table looked so....unformated I guess we just blindly overlooked your post about it. Commented Jan 31, 2018 at 6:49
  • @DevilsHnd No, thank you! Your post helps a lot. I'm just a bit confused on the converting to string part. Can you explain that a little more, please?
    – twobzombie
    Commented Jan 31, 2018 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.