print in a loop

171 views (last 30 days)
Ayda
Ayda on 6 Dec 2011
Answered: VADTHYAVATH on 22 Feb 2024
Good morning\evening
how can i print p[1], p[2]... 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

Answers (2)

Paulo Silva
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 Comments
Ayda
Ayda on 7 Dec 2011
thanks Mr. Paulo Silva for answering me
it is not a homework question
I just ask because I'am working in senio project
for question 2,, can it be done using for loop ?
Paulo Silva
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.

Sign in to comment.


VADTHYAVATH
VADTHYAVATH on 22 Feb 2024
how to print 1 to 10 numbers using for loop

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!