Creating a vector with nested for loops and a while loop

1 次查看(过去 30 天)
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.

采纳的回答

per isakson
per isakson 2018-5-22
编辑:per isakson 2018-5-22
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Debugging and Analysis 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by