Creating Loop using vector output

2 visualizzazioni (ultimi 30 giorni)
Matthias Bossenbroek
Matthias Bossenbroek il 5 Ott 2018
Modificato: Stephen23 il 5 Ott 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

Risposte (1)

Stephen23
Stephen23 il 5 Ott 2018
Modificato: Stephen23 il 5 Ott 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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by