Creating a vector from nested for loops
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Cris LaPierre
2020-3-26
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 个评论
Cris LaPierre
2020-3-26
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
2020-3-26
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.
另请参阅
类别
在 Help Center 和 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!