# setting up a variable matrix

I am trying to set up a variable matrix, where I have a variable x that goes from 0 to 2 and a variable z that goes from 0 to 2. I have two other variables m and n that depend on both x and z. How should I go about setting up a variable matrix?

So I typed it up in matlab, how would I transfer the code in Mathematica? a is a constant

%Defining vatiables
x=[-2*a:.01*3*a:2*a];
z=[0:.005*3*a:2*a];

%Creates variable matrix
for i=1:length(z);
for j=1:length(x);
xx(i, j)=x(j);
zz(i, j)=z(i);
end
end

%A loop to find the stresses, where the stress (sz,sx,sy, and txy) is dependent on both m and n

for i=1:length(x);
for j=1:length(z);
m(j, i)=(0.5*(((a^2-xx(j, i)^2+zz(j, i)^2).^2+4.*xx(j, i)^2.*zz(j, i)^2).^0.5+(a.^2.-xx(j, i)^2+zz(j, i)^2))).^0.5;
n(j, i)=(0.5*(((a^2-xx(j, i)^2+zz(j, i)^2).^2+4.*xx(j, i)^2.*zz(j, i)^2).^0.5-(a.^2.-xx(j, i)^2+zz(j, i)^2))).^0.5;
if x(i) < 0
n(j, i)=-n(j, i);
end
sx(j, i)=(-Ph/a)*(m(j, i)*((1+((zz(j, i)^2+n(j, i)^2)/(m(j, i)^2+n(j, i)^2))))-2.*zz(j, i));
sz(j, i)=(-Ph/a)*m(j, i)*((1-((zz(j, i)^2+n(j, i)^2)/(m(j, i)^2+n(j, i)^2))));
sy(j, i)=v1*(sx(j, i)+sz(j, i));
txz(j, i)=(-Ph/a).*n(j, i)*((m(j, i)^2-zz(j, i)^2)./(m(j, i)^2+n(j, i)^2));
tmax(j, i)=0.5*abs(sx(j, i)-sz(j, i));
end
end

• Specify the constraints on the matrix: dimensions, locations for variables, etc. Otherwise we cannot help you. Commented Oct 26, 2018 at 22:32
• Maybe try to learn a little about the syntax of Mathematica. I Commented Oct 27, 2018 at 1:25
• What have you tried? Commented Oct 27, 2018 at 12:11
• I have tried using a couple of For loops, but that really went nowhere. The main problem that i'm having is learning mathematica. Ill try looking into the document to translate the code. What do you mean by syntax of Mathematica?
– Alc
Commented Oct 27, 2018 at 14:59

Here is something to help get you started: the "defining variables" and "creating matrix" portions of your code can be done like this:

x = Range[-2 a, 2 a, 0.01*3*a];
z = Range[0, 2 a, 0.005*3*a];
zz = ConstantArray[z[[Range[Length[z]]]], Length[x]];
xx = ConstantArray[x[[Range[Length[x]]]], Length[z]];


resulting two 134 by 134 matrices xx and zz containing the symbol a. If you don't understand some of the syntax (like the double [[ or Range or ConstantArray), place the cursor on them and you can find out their meaning by invoking F1 (help).

• Awesome, thank you so much for help. This makes a lot more sense now than what I was trying to do. So would I have to do anything else to solve for sy,sy, and sx or could i just plug the values xx and zz into the equation. The end goal is make a contour plot. Im assuming that mathematica would be fine with plotting this. Correct?
– Alc
Commented Oct 28, 2018 at 21:24
• With a little luck,m you should be able to write the equations for sy and sx etc in analogous matrix form. It's a lot like vectorization in Matlab, but considerably more flexible. Commented Oct 29, 2018 at 0:26