Creating Loop using vector output

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 个)

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

类别

帮助中心File 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