print in a loop

조회 수: 144 (최근 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 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