필터 지우기
필터 지우기

Creating a vector with nested for loops and a while loop

조회 수: 1 (최근 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

추가 답변 (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