Creating a vector from nested for loops
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi
So I basically want to create a column vector from two nested for loops
Initially, i planned my code to be like
for i =1:n
for j=1:m
P=(j-1)*n+i;
b(P,1)=T((i-1)*dx,(j-1)*dy); %%T is an anonymous function T=@(x,y) 20*cos(x)*sin(y);
end
end
But when I run that I get a singular row vector (rank 1) and I can't use that for later on when I need to divide it by a matrix A.
What am I doing wrong over here?
Many thanks
0 comentarios
Respuestas (1)
Cris LaPierre
el 26 de Mzo. de 2020
Two ideas come to mind.
for i =1:n
for j=1:m
b(i,j)=...
end
end
b=b(:);
Another way might be to add the new result to the end of b
b=[];
for i =1:n
for j=1:m
b=[b; T((i-1)*dx,(j-1)*dy)];
end
end
7 comentarios
Cris LaPierre
el 26 de Mzo. de 2020
Let's walk through the code.
i=1
j=1
store the current value of T in b(1,1)
i=1
j=2
store the current value of T in b(2,1)
...
i=1
j=m
store the current value of T in b(m,1)
i=2
j=1
What row of b should the value of T be stored in? It should be m+1, right?
Plug the current values of i and j into my equation for P.
P=(2-1)*m + 1 which equals m+1
Test this for the first case (i=1,j=1).
P=(1-1)*m + 1 or 1.
The outer loop increments one, then the inner loop increments though all it's loops. You wrote P for the opposite case - the outer loop running through all it's values and then the inner loop increments one.
Cris LaPierre
el 26 de Mzo. de 2020
As for P, you're doing something somewhere else that is not shown that is causing your error. You can read more about that here, but that's a separate issue that is not related to the question asked in this post.
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!