Creating a vector from nested for loops

조회 수: 6 (최근 30일)
Maaz Madha
Maaz Madha 2020년 3월 26일
댓글: Cris LaPierre 2020년 3월 26일
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

답변 (1개)

Cris LaPierre
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
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
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 CenterFile 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