Effacer les filtres
Effacer les filtres

while loop only diving last result

2 vues (au cours des 30 derniers jours)
Matlabbey
Matlabbey le 14 Août 2012
Hi,
I have some code within a while loop. Let's say the loop runs 10 times and I want to find Xstar for each of those 10 times. The code will do this, but I want to create a vector to hold each of these 10 values so I don't have to read through and find them. After the code runs,the value stored onto Xstar is the value for the 10th iteration. I want to keep it that way, but also add a new vector that holds ALL of the Xstar values.
Thank you!!
  1 commentaire
Azzi Abdelmalek
Azzi Abdelmalek le 14 Août 2012
post your code

Connectez-vous pour commenter.

Réponses (2)

Oleg Komarov
Oleg Komarov le 14 Août 2012
count = 0; % initialize counter
out = zeros(100,1); % preallocate (not always possible with while)
while count < 100
count = count + 1; % increment counter
out(count) = rand; % allocate result into preassigned space in out
end
  4 commentaires
Walter Roberson
Walter Roberson le 14 Août 2012
Xstar = {}
while condition
thousands of lines of code
Xstar{end+1} = equation;
end
Note: if you can make reasonable guesses about the number of iterations, it is best to pre-allocate the cell array and use a counter instead of "end+1".
guess_length = 100;
Xstar = cell(guess_length,1);
count = 0;
while condition
thousands of lines of code
count = count + 1;
Xstar{count} = equation;
end
if count < guess_length %trim off unused portions
Xstar(counts+1:end) = [];
end
Matlabbey
Matlabbey le 14 Août 2012
Thanks!! That did the trick!

Connectez-vous pour commenter.


Azzi Abdelmalek
Azzi Abdelmalek le 14 Août 2012
v=[];
while condition
Xstar=
v=[v Xstar]
end

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by