Creating a vector with nested for loops and a while loop

5 ビュー (過去 30 日間)
Colin Lynch
Colin Lynch 2018 年 5 月 22 日
コメント済み: Colin Lynch 2018 年 5 月 22 日
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
  1 件のコメント
Colin Lynch
Colin Lynch 2018 年 5 月 22 日
Man, you made that look really easy! Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by