While loop runs inconsistently, most often generating a vertcat error.

1 vue (au cours des 30 derniers jours)
Hey everyone, any help or tips y'all could give me would be greatly appreciated. I'm running a nested loop code to produce a 3D plot containing multiple lines generated from the nested portion of the code. The z coordinate is constant for each line, and only changes between lines. The issue I'm running into is that when I run the code I get a vertcat error more often than not, due to the z array being 1x19 double, while the x and y arrays are 1x18 double. I understand why the vertcat error causes the code to stop, but I don't understand why the vertcat error is being created in the first place. Below is a picture from a successful run to show the desired result, as well as my code. Any clue what's going wrong? I assume it's some issue with how I'm incrementing the value of z. I've tried relocating the incrementing line higher in the code since I thought maybe it was generating a final z value after x and y had finished, causing the z array to have one value more than the other two. However, that hasn't removed the error, and if that was the case then I would think the code would have the vertcat error every time it ran instead of only sometimes.
clc
clear all
z = 0; %initializing starting z value
k = 1;
while z <= 0.16
x = 0+(4-0).*rand(1,1); %initializing starting x value
L = .25; %0.25mm segment length between nodes
y = 0; %initializing starting y value
i = 1;
while y<=4
x(i+1) = x(i) + (.25*sind(-40+(40+40).*rand(1,1)));
y(i+1) = y(i) + (.25*cosd(-40+(40+40).*rand(1,1)));
z(i+1) = z(i);
i = i + 1;
end
xyz{k} = [x;y;z];
plot3(x,y,z,'o')
axis([-1 5 -1 5 0 0.16])
hold on
fnplt(cscvn(xyz{k}(:,[1:end])),'r',2)
z = z+0.01;
k = k+1;
end
hold off

Réponse acceptée

Sean Clifton
Sean Clifton le 22 Mai 2020
Nevermind, I embarrasingly missed the easy solution here. I switched from a While loop to a for loop to increment the z values. Below's the code that ended up solving the problem:
clc
clear all
z = 0; %initializing starting z value
k = 1;
for z = 0:0.01:0.16
x = 0+(4-0).*rand(1,1); %initializing starting x value
L = .25; %0.25mm segment length between nodes
y = 0; %initializing starting y value
i = 1;
while y<=4
x(i+1) = x(i) + (.25*sind(-40+(40+40).*rand(1,1)));
y(i+1) = y(i) + (.25*cosd(-40+(40+40).*rand(1,1)));
z(i+1) = z(i);
i = i + 1;
end
xyz{k} = [x;y;z];
plot3(x,y,z,'o')
axis([-1 5 -1 5 0 0.16])
hold on
fnplt(cscvn(xyz{k}(:,[1:end])),'r',2)
k = k+1;
end
hold off

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by