Creating a vector with nested for loops and a while loop
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Colin Lynch
le 22 Mai 2018
Commenté : Colin Lynch
le 22 Mai 2018
Hello everyone!
I am attempting to an 8 element long vector that looks like this:
vector = [2 4 8 16 32 64 128 256]
To do this, I am nesting a while loop inside of two for loops like this:
close all;
clearvars;
vector = zeros(1,2*2*2);
c = 0;
d = 1;
for a = 1:2
for b = 1:2
while c < 2
d = d*2;
vector(?) = d;
c = c+1;
end
end
end
Does anyone know what I can put in the place of the question mark so that every time we run through the loops, it adds the next value of d as the next element in the vector? Or are there more lines of code that I need to add to make this happen? Right now the code just keeps overwriting the first two elements of the vector and I don't know how to make it jump to the next elements.
Thank you in advanced, and have a great day!
Sincerely, Colin
P.S. Oh, I know that this is an extremely convoluted way of accomplishing this task; this bit of code is just meant to represent a much larger program I've written that doesn't fit into this web page.
0 commentaires
Réponse acceptée
per isakson
le 22 Mai 2018
Modifié(e) : per isakson
le 22 Mai 2018
One way
>> cssm
ans =
2 4 8 16 32 64 128 256
>>
where
function vector = cssm
vector = zeros(1,2*2*2);
c = 0;
d = 1;
ix = 0;
for a = 1:2
for b = 1:2
c = 1;
while c <= 2
d = d*2;
ix = ix+1;
vector(ix) = d;
c = c+1;
end
end
end
end
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!