MATLAB Answers

# Creating a vector from nested for loops

24 views (last 30 days)
Maaz Madha on 26 Mar 2020
Commented: Cris LaPierre on 26 Mar 2020
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 CommentsShowHide -1 older comments

Sign in to comment.

### Answers (1)

Cris LaPierre on 26 Mar 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 CommentsShowHide 6 older comments
Cris LaPierre on 26 Mar 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.

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!