How to store vectors generated in a while loop in a single vector?

I am trying to create a vector with all the data generated from while loop iterations. I would like to generate a vector with all Y vectors generated (in line) and do the same for the X vector in the second while loop. Just to be clear, the first while loop will generate Y vectors with 101 columns, then 100... all the way to 1 column. I want to create a vector with all the numbers from each vector in line, so I would have a vector with 5151 columns. Is that possible?
X = [0:0.01:1];
m = 1;
nf = 101;
while m <= nf
Y = [0:0.01:1-X(m)];
m = m+1;
end
n = 0;
i = 0.01;
while 1-n*i >= 0
X = [0:0.01:1-n*i]
n = n+1;
end

回答(1 个)

See if this does what you want:
maxIterations = 500; % Failsafe for the while loop
X = [0:0.01:1];
m = 1;
nf = 101;
Y = [];
while m <= nf && m < maxIterations
numberOfElements = nf - m + 1;
thisY = linspace(0, 1 - X(m), numberOfElements);
m = m + 1;
Y = [Y, thisY];
fprintf('thisY is %d elements long and the total vector is %d elements long (so far).\n', ...
length(thisY), length(Y));
end
n = 0;
i = 0.01;
m = 1;
X = [];
while 1-n*i >= 0 && m < maxIterations
numberOfElements = nf - m + 1;
if numberOfElements <= 0
break;
end
thisX = linspace(0, 1-n*i, numberOfElements);
X = [X, thisX];
% n = n+1;
m = m + 1;
fprintf('thisX is %d elements long and the total vector is %d elements long (so far).\n', ...
length(thisX), length(X));
end

2 个评论

It worked perfectly! Thanks a lot! I didn't need to use the linspace function though, just the addition of the
Y = [];
while ...
Y = [Y,thisY]
end
#was necessary

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by