Java code to Matlab
4 views (last 30 days)
Show older comments
Hello all,
I am trying to convert some Java code into matlab code and I am a little bit stuck. I have used matlab to some extent, but I do not use it full time. I am a bit stuck on how to void the variables w and a. I am also unsure of how to incorporate the less than i in the for loop. Anyways the code I would like to convert is:
void Concentrated(double w, double a)
{
// compute reaction
double b=L-a;
rr = w;
mr = w*a;
// compute shear, moemnt and deflection till the point a
for (i=0;i<numPoints;++i)
{
if (x[i]<b)
{
v[i] = 0.;
m[i] = 0.;
y[i] = -rr/(6.*E*I)*(-a*a*a+3.*a*a*L-3.*a*a*x[i]);
}
else
{
v[i] = -rr;
m[i] = -rr*(x[i]-b);
y[i] = -rr/(6*E*I)*(Math.pow(x[i]-b,3)-3*a*a*(x[i]-b)+2*a*a*a);
}
}
}
0 Comments
Answers (3)
Geoff Hayes
on 12 Nov 2014
Christopher - I am not all that clear on what you mean by to void the variables w and a. Your MATLAB function signature would be near identical to that for the Java version. Just do something like
function Concentrated(w,a)
Since your Java function doesn't return anything (void) then there is nothing to declare for the MATLAB function either.
As for the for loop (which seems to be missing an integer declaration for i, perhaps the data type is inferred as integer if one is not declared)
for (i=0;i<numPoints;++i)
becomes
for k=0:numPoints-1
I've used k as the index variable since i and j are representation of the imaginary number in MATLAB so it is good practice to avoid using these names for indexing variables. The syntax for the for loop is clear - k starts at zero and ends at numPoints-1. We don't need to specify the increment for k at each iteration (the default is one).
Just be wary - MATLAB arrays are one-based and the () brackets are used to access elements in an array. So if myArray is a row vector/array, then the first element is accessed with
myArray(1)
the second with
myArray(2)
etc., and the last can be accessed simply with
myArray(end)
Hope that the above helps!
0 Comments
Christopher
on 12 Nov 2014
1 Comment
Geoff Hayes
on 12 Nov 2014
Looking closer at the code you pasted in your question, there seems to be a number of local variables that are not defined. What is v, L, x, y, etc.? How does this code compile without error?
MUHAMMAD Ateeb
on 5 Jun 2021
Edited: Geoff Hayes
on 8 Jun 2021
import java.lang. *;
import java.util.Random;
public class Monte {
public static void main(String argv[])
Random r new Random(); =
int n
double s0 = 0;
double ds = 0;
for (int i=0; i<n; ++i) {
double x = r.nextDouble();
double f = x*x;
s0 += £;
ds += f*f;
{
}
s0 /= n;
ds /= n;
ds = Math.sqrt (Math.abs (ds-s0*s0)/n);
System.out.println("S = " + S0 + + ds);
}
0 Comments
See Also
Categories
Find more on Call Java from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!