Creating Loop using vector output

2 views (last 30 days)
Matthias Bossenbroek
Matthias Bossenbroek on 5 Oct 2018
Edited: Stephen23 on 5 Oct 2018
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

Answers (1)

Stephen23
Stephen23 on 5 Oct 2018
Edited: Stephen23 on 5 Oct 2018
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!