Creating a vector with nested for loops and a while loop

5 views (last 30 days)
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.

Accepted Answer

per isakson
per isakson on 22 May 2018
Edited: per isakson on 22 May 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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!