How can I distinguish between array structure in JAVA and Matalb? (code conversion)

2 views (last 30 days)
I have a java code and I want to convert it as matlab code:
public int[] multiplyEncrypted(int[] num1, int[] num2){
int[] result = new int[num1.length + num2.length];
for(int i=0; i < result.length; i++){
result[i] = 0;
}
for(int i=0; i < num1.length; i++){
for(int j=0; j < num2.length; j++){
int index = i + j + 1;
int mult = ((num1[i]) * (num2[j])% M);
result[index] = result[index] + mult;
}
}
return result;
}
I tried to convert it to matlab but I have problem to understand how far the structure and dimensions of both JAVA and matlab works!!
Could anyone help me to solve this?

Accepted Answer

Geoff Hayes
Geoff Hayes on 18 Apr 2014
Hi Abdulatif,
Based in the java code that you have included in your question, the inputs to the function are two vectors, num1 and num2. The MATLAB signature for this function would then be:
function [result] = multiplyEncrypted(num1, num2)
So almost the same as the Java signature less the data types and array indicator. In the java code, you can get the length (number of elements) of the array simply (as shown in the code) by calling the length on the input: num1.length. The equivalent in MATLAB is length(num1) .
Accessing the elements in MATLAB will be similar but you have to be aware that the array indexing is one-based as opposed to the Java zero-based. So if the length of num1 is 15, then you can access the 15 elements (in Java) as num1[0], num1[1], num1[2],…,num1[14]. The equivalent in MATLAB is num1(1), num1(2),…,num1(15).
Hope that this helps!
Geoff
  3 Comments
Geoff Hayes
Geoff Hayes on 18 Apr 2014
Hi Abdulatif,
Im sure that the array positions for 2-D arrays should still be the same with the only difference being that the java arrays are zero-based and the matlab arrays one-based. If mtrx is a 2D array in java then the first element in the first row first column is accessed by mtrx[0][0]. The equivalent in java would be mtrx(1,1). The first dimension (in both) would correspond to the rows and the second dimension in both would correspond to the columns…so no difference between the two function.
You don't have to define the number of columns and rows of a vector or matrix input to a MATLAB function. They can be passed as in the sample signature above. It is when you create the matrix or vector that you define the dimensions:
vctr = zeros(1,15); % row vector with 15 columns mtrx = zeros(12,19); % matrix with 12 rows and 19 columns
To get the dimension of the vector just use length. So in this case, length(vctr) would return 15. To get the dimensions of the mtrx (if you know that it is 2D) just do: [r,c] = size(mtrx);. The size function will return the number of rows (r, first dimension) and the number of columns (c, second dimension).
Geoff

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!