Creating Loop using vector output

조회 수: 2 (최근 30일)
Matthias Bossenbroek
Matthias Bossenbroek 2018년 10월 5일
편집: Stephen23 2018년 10월 5일
Hi,
Im working on a loop that uses the output of the loop before. With numbers this was no issue but now i'm using vectors. and because my index is no vector this is a problem. The function will multiply x(i) * vector(3;2;1). (15 times) with x(0) = [1;1;1]. But i keep on getting errors. Who knows how i can fix it?
k = 1
x(k-1)= [1;1;1]
while k<14
k = k +1
x(k)= x(k-1)*[3;2;1]
end

답변 (1개)

Stephen23
Stephen23 2018년 10월 5일
편집: Stephen23 2018년 10월 5일
The problem has nothing to do with loops, it occurs solely because you are trying to allocate multiple elements into one element:
x(k) = x(k-1)*[3;2;1]
An element of a numeric matrix contains one value. You cannot put multiple elements into one element of a matrix.
The indexing here also makes no sense, because indexing starts with one:
k = 1;
x(k-1) = [1;1;1]
I suspect that you want to use subscript indexing, something like this:
k = 1;
mat = nan(3,14);
mat(:,k) = [1;1;1];
while k<14
k = k+1;
mat(:,k)= mat(:,k-1).*[3;2;1];
end
although really using a for loop would be preferable:
N = 14;
mat = nan(3,N);
mat(:,1) = [1;1;1];
for k = 2:N
mat(:,k)= mat(:,k-1).*[3;2;1];
end

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by