Nguyen Hoai Thanh
Nguyen Hoai Thanh

Reputation: 359

MATLAB function in Java

I tried to run a simple matlab code in java (I'm new to Java).

In matlab, I created this function :

Function [y] = square[x]
  y = sqrt(x)
end

I named the class: square

But when I run the function in Eclipse, I couldn't make it work.

Here is the code in Eclipse:

import square.*;
import com.mathworks.*;
import com.mathworks.toolbox.javabuilder.*;

public class square {
/**
 * @param args
 */
    public static void main(String[] args) {
        square x = new square();
        Double z =  x.square(8);
    }
}

The error is: The method square(int) is undefined for the type square

Any idea? Thanks so much!

Upvotes: 1

Views: 368

Answers (2)

ShaMan-H_Fel
ShaMan-H_Fel

Reputation: 2209

The problem you have is that you do not have defined the method square. That is exactly what the compiler complains about.

Define it like this to return a Double object:

private Double square(int x) {
    // do whatever you like here
}

However I think it will be better if you use the primitive double type for simple tests (just be aware for the precision).

Another option is to use one of the methods defined in the Math utility class.

Upvotes: 0

Adil
Adil

Reputation: 582

You can use the Math.Pow() function in Java to square a number. If you wanted to write your own function, you could do:

class Mymaths
{
public static double Square(double exponent, double number)
{
  return Math.pow(number,exponent);
}
}

Then you could use that inside your main method:

public static void main(String[] args)
{
  Mymaths.Square(2.0,8.0); //should return 64
}

Sorry if I misunderstood, but that's what I read.

Upvotes: 1

Related Questions