print in a loop

162 ビュー (過去 30 日間)
Ayda
Ayda 2011 年 12 月 6 日
回答済み: VADTHYAVATH 2024 年 2 月 22 日
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

回答 (2 件)

Paulo Silva
Paulo Silva 2011 年 12 月 6 日
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 件のコメント
Ayda
Ayda 2011 年 12 月 7 日
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 2011 年 12 月 7 日
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.

サインインしてコメントする。


VADTHYAVATH
VADTHYAVATH 2024 年 2 月 22 日
how to print 1 to 10 numbers using for loop

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by