# [Beginner] Plotting 3D graphs, but "Error using plot3 Vectors must be the same length."

1 view (last 30 days)
ABCDEFG HIJKLMN on 21 Oct 2021
Edited: Cris LaPierre on 25 Oct 2021
i want to plot two 3D functions (Z_1 and Z_2) in one graph, where
X = linspace(x_1_min,x_1_max);
Y = linspace(x_2_min,x_2_max);
and I am calculating Z_1 and Z_2 with
for i=1:1:100
for j=1:1:100
Z_sigma_1 = ((1 + X(i)) * sqrt(1 + X(i)^2)) / (2 * sqrt(2) * X(i) * Y(j));
Z_sigma_2 = ((X(i) - 1) * sqrt(1 + X(i)^2)) / (2 * sqrt(2) * X(i) * Y(j));
Z_1 = [Z_1 Z_sigma_1];
Z_2 = [Z_2 Z_sigma_2];
end
end
I get the error that the vectors must be the same size, but how could I ever not have more elements in Z_1 and Z_2 than in X and Y? The number of elements in Z_1 and Z_2 is the same and would always be the product of the number of elements in X and Y! What I am doing wrong?
Thanks in advance for the help!
The figure is plotted as follows
figure (1)
grid on
hold on
plot3(X,Y,Z_1, '-r','DisplayName','sigma1');
plot3(X,Y,Z_2, '-m','DisplayName','sigma2');
xlabel('x_1')
ylabel('x_2')
zlabel('sigma')
legend show

Cris LaPierre on 21 Oct 2021
Edited: Cris LaPierre on 21 Oct 2021
You appear to have left out the code that initializes Z_1 and Z_2. Depending how you initialize them, Z_1 and Z_2 could have more elements than X and Y.
To ensure Z_1 and Z_2 are the size you expect, try the following.
Z_1 = [];
Z_2 = [];
for i=1:1:100
for j=1:1:100
Z_sigma_1 = ((1 + X(i)) * sqrt(1 + X(i)^2)) / (2 * sqrt(2) * X(i) * Y(j));
Z_sigma_2 = ((X(i) - 1) * sqrt(1 + X(i)^2)) / (2 * sqrt(2) * X(i) * Y(j));
Z_1 = [Z_1 Z_sigma_1];
Z_2 = [Z_2 Z_sigma_2];
end
end
##### 2 CommentsShowHide 1 older comment
Cris LaPierre on 25 Oct 2021
It starts them out as empty. The only reason I see that they would now not be the correct length is if your equations for Z_sigma_1 or Z_sigma_2 are returning more than one value each time. Please check there.

R2021a

### Community Treasure Hunt

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

Start Hunting!