print in a loop
94 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
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 个评论
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!