MATLAB: How do i create a program that, depending on the input value would create more or less variables

arrayindexindexingmatrix array

I have the following code i did for calculating location of earthquakes based on the information of different stations, it isn't complete yet but it's something. How do i create an index or array structure in which i don't have to manually insert da,db,dc or dtax0, dtay0 and so on, but give a number and the code creates the variables depending on how high the number is, so for example if i put a for k=1:1 it just creates da,dtat0,dtax0,dtay0 and dtaz0 but if i put an 'if p=2' it creates da,db,dtax0,dtbx0 and so on.
da=((A(1,1)-m0(2))^2+(A(2,1)-m0(3))^2+(A(3,1)-m0(4))^2)^(1/2);
db=((A(1,2)-m0(2))^2+(A(2,2)-m0(3))^2+(A(3,2)-m0(4))^2)^(1/2);
dc=((A(1,3)-m0(2))^2+(A(2,3)-m0(3))^2+(A(3,3)-m0(4))^2)^(1/2);
dd=((A(1,4)-m0(2))^2+(A(2,4)-m0(3))^2+(A(3,4)-m0(4))^2)^(1/2);
dtat0=1;
dtax0=-(A(1,1)-m0(2))/v*da;
dtay0=-(A(2,1)-m0(3))/v*da;
dtaz0=-(A(3,1)-m0(4))/v*da;
dtbt0=1;
dtbx0=-(A(1,2)-m0(2))/v*db;
dtby0=-(A(2,2)-m0(3))/v*db;
dtbz0=-(A(3,2)-m0(4))/v*db;
dtct0=1;
dtcx0=-(A(1,3)-m0(2))/v*dc;
dtcy0=-(A(2,3)-m0(3))/v*dc;
dtcz0=-(A(3,3)-m0(4))/v*dc;
dtdt0=1;
dtdx0=-(A(1,4)-m0(2))/v*dd;
dtdy0=-(A(2,4)-m0(3))/v*dd;
dtdz0=-(A(3,4)-m0(4))/v*dd;
The da,db,dc,dd are the distances and the rest are the partial derivates

Best Answer

Forget about dynamically accessing variable names, simply vectorize your code and you will immediately be on the way to writing simpler, more efficient MATLAB code. Rather than these:
da=((A(1,1)-m0(2))^2+(A(2,1)-m0(3))^2+(A(3,1)-m0(4))^2)^(1/2);
db=((A(1,2)-m0(2))^2+(A(2,2)-m0(3))^2+(A(3,2)-m0(4))^2)^(1/2);
dc=((A(1,3)-m0(2))^2+(A(2,3)-m0(3))^2+(A(3,3)-m0(4))^2)^(1/2);
dd=((A(1,4)-m0(2))^2+(A(2,4)-m0(3))^2+(A(3,4)-m0(4))^2)^(1/2);
Just write this:
dV = sqrt((A(1,:)-m0(2)).^2+(A(2,:)-m0(3)).^2+(A(3,:)-m0(4)).^2);
And rather than these:
dtax0=-(A(1,1)-m0(2))/v*da;
dtbx0=-(A(1,2)-m0(2))/v*db;
dtcx0=-(A(1,3)-m0(2))/v*dc;
...
do something like this (the exact code you need depends on the size of v):
dtx0 = -(A(1,:)-m0(2))./v.*d;
or even do all of x, y and z at once, something like:
dt0 = -bsxfun(@minus,A(1,:),m0(:))./v.*d;
The actual operations you require depend on the sizes and classes of the arrays.
Knowing how to manipulate matrices/arrays is fundamental to using MATLAB. The name MATLAB comes from "MATrix LABoratory" and not from "puts the data into lots of separate variable and make it difficult to work with". The introductory tutorials are a good place to start learning how to use matrices effectively:
You should also read these:
Experiment! The more you practice, the more it will make sense and the better you can use matrices.