# print in a loop

232 views (last 30 days)
Ayda on 6 Dec 2011
Good morning\evening
how can i print p, p... p[n] using for loop
I couldn't print using
for i=1:3
p[i]
end
OR
for i=1:3
p[i]
end
What is the correct way?
And ONE more question if a have array p =[p1;p2;p3] and have array q =[1 2 ; 3 4 ; 5 6] how can I let p1=[1 2], p2=[ 3 4] and p3=[5 6]
Regards

Paulo Silva on 6 Dec 2011
fprintf('\n')
for i=1:3
fprintf('p[%d] ',i)
end
fprintf('\n')
or a fancy version with comma
fprintf('\n')
for i=1:3
fprintf('p[%d]',i)
if i~=3
fprintf(', ')
end
end
fprintf('\n')
2 question
q =[1 2 ; 3 4 ; 5 6]
p1=q(1,:);
p2=q(2,:);
p3=q(3,:);
p =[p1;p2;p3]
I hope that the question isn't homework related, don't just copy the code, try to understand how it works and if you have any further question just write a comment
##### 2 CommentsShowHide 1 older comment
Paulo Silva on 7 Dec 2011
Yes it can be done but you should read this first http://www.mathworks.com/matlabcentral/answers/143-how-do-i-make-a-series-of-variables-a1-a2-a3-a10
The way you should do it is:
q =[1 2 ; 3 4 ; 5 6]
p=cell(3,1); %preallocate one cell to store the result
for n=1:size(q,1)
p{n}=q(n,:); %save every line into each element of p, so p1 is p{1}
end
Instead of making a mess by creating several variables you do the same with just one variable, it's easy to work with and understand.