MATLAB: Help with for loop calling values of variables from an array.

for loops

%create a for loop for the function
b={.25, .25, .5};
d={.25, .75, .5};
for n=1:1:3;
p=cell2mat(b(n));
z=cell2mat(d(n));
Ca = 4*pi^2/((pi^2-8)*(p^2-z*z)-2*pi*(pi-2)*p+pi^2);
x1 = 0:0.01:(p/2);
y1 = Ca*sin(pi*x1/p);
x2 = p/2:0.01:(1-z)/2;
y2 = Ca;
x3 = (1-z)/2:0.01:(1+z)/2;
y3 = Ca*cos(pi*(x3-(1-z)/2)/z);
x4 = (1+z)/2 :0.01:1-p/2;
y4 = -Ca;
x5 = (1-p/2):0.01:1;
y5 = Ca*sin(pi*(x5-1)/p);
x = [x1 x2 x3 x4 x5];
y = [y1 y2 y3 y4 y5];
plot(x,y);
hold on;
end;
I keep getting vectors must be the same length. The code works if I input values for p and z one by one, but not when in the for loop. Am I missing something? It is supposed to plot the acceleration graph for 3 of the SCCA familes of function.

Best Answer

size of x, y were not same in your code. Tp plot vectors x, y must have same dimensions.
b={.25, .25, .5}; d={.25, .75, .5};
for n=1:1:3;
p=cell2mat(b(n));
z=cell2mat(d(n));
Ca = 4*pi^2/((pi^2-8)*(p^2-z*z)-2*pi*(pi-2)*p+pi^2);
x1 = 0:0.01:(p/2); y1 = Ca*sin(pi*x1/p);
x2 = p/2:0.01:(1-z)/2; y2 = ones(size(x2))*Ca;
x3 = (1-z)/2:0.01:(1+z)/2; y3 = Ca*cos(pi*(x3-(1-z)/2)/z);
x4 = (1+z)/2 :0.01:1-p/2; y4 = -ones(size(x4))*Ca;
x5 = (1-p/2):0.01:1; y5 = Ca*sin(pi*(x5-1)/p);
x = [x1 x2 x3 x4 x5]; y = [y1 y2 y3 y4 y5];
plot(x,y);
hold on;
end