Home > Net >  How Can I Convert That Piece of Matlab Code to Java?
How Can I Convert That Piece of Matlab Code to Java?

Time:04-07

I have a piece of Matlab code but could not find out how to convert to a Java code. What does this row mean? How can be converted to Java?

Matlab code:

b = all(x <= y) && any(x<y);

Hint: x = [1,2,3,4,5], y = [5,4,3,2,1] What is b as the result?

CodePudding user response:

You can use Java Streams like in

var x = new int[] {1, 2, 3, 4, 5};
var y = new int[] {5, 4, 3, 2, 1};
var b =    IntStream.range(0, x.length).allMatch(i -> x[i] <= y[i])
        && IntStream.range(0, x.length).anyMatch(i -> x[i] <  y[i]);

not handling x and y having different sizes!

CodePudding user response:

From the matlab official site:

A <= B returns a logical array with elements set to logical 1 (true) where A is less than or equal to B; otherwise, the element is logical 0 (false).

Up to this you have 11100 in the first comparison.

B = all(A) tests along the first array dimension of A whose size does not equal 1, and determines if the elements are all nonzero or logical 1 (true). In practice, all is a natural extension of the logical AND operator.

So all(x <= y) must return 0.

B = any(A) tests along the first array dimension of A whose size does not equal 1, and determines if any element is a nonzero number or logical 1 (true). In practice, any is a natural extension of the logical OR operator.

So any(x < y) should be 1.

&& is AND

The rest is up to you

  • Related