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

9 Ansichten (letzte 30 Tage)
Antonio Alves
Antonio Alves am 5 Apr. 2021
Kommentiert: Image Analyst am 5 Apr. 2021
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

Antworten (1)

Image Analyst
Image Analyst am 5 Apr. 2021
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 Kommentare
Antonio Alves
Antonio Alves am 5 Apr. 2021
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
Image Analyst
Image Analyst am 5 Apr. 2021
I needed to, otherwise I got 5150 elements for Y instead of 5151 because of this reason I believe:

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by