1

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!

2
  • 1
    shouldnt it be Square x = new Square(); Double z = x.square(8);? I dont know the matlab stuff but in your class square does a method square not exists... Commented Feb 15, 2012 at 10:47
  • could it be the problem that your java class has the same as the one created by matlab? Commented Feb 15, 2012 at 13:08

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I just wanna test a simple matlab code in Java, so that I have the idea how to let matlab code worked in Java. Thanks.
0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.