Why the loop return only the last element ?

1 回表示 (過去 30 日間)
Luiz Felippe
Luiz Felippe 2013 年 4 月 10 日
I'm trying to change the size of subplots using a for loop.So what I really want to do is this:
clear
n=9;
pos=cell(1,n);
for i=1:n
a(i)=subplot(n,1,i);
pos{i}= get(a(i),'position');
if i<9
set(gca,'xtick',[])
end
pos{i}(1,4)=(pos{i}(1,4))/2;
set(a(i),'position',pos{i});
end
pos{8}(1,2)=(pos{8}(1,2)) - 0.045;
pos{7}(1,2)=(pos{7}(1,2)) - 0.09;
pos{6}(1,2)=(pos{6}(1,2)) - 0.1350;
pos{5}(1,2)=(pos{5}(1,2)) - 0.18;
pos{4}(1,2)=(pos{4}(1,2)) - 0.2250;
pos{3}(1,2)=(pos{3}(1,2)) - 0.2700;
pos{2}(1,2)=(pos{2}(1,2)) - 0.3150;
pos{1}(1,2)=(pos{1}(1,2)) - 0.3600;
set(a(8),'position',pos{8});
set(a(7),'position',pos{7});
set(a(6),'position',pos{6});
set(a(5),'position',pos{5});
set(a(4),'position',pos{4});
set(a(3),'position',pos{3});
set(a(2),'position',pos{2});
set(a(1),'position',pos{1});
But,I want to do this in a easier way .So I tried make all this using just a for loop :
clear
n=9;
pos=cell(1,n);
for i=1:n
a(i)=subplot(n,1,i);
pos{i}= get(a(i),'position');
if i<9
set(gca,'xtick',[])
end
pos{i}(1,4)=(pos{i}(1,4))/2;
for d=8:-1:0
y(d+1)=0.045*d;
t=fliplr(y);
end
pos{i}(1,2)=(pos{i}(1,2))-t(i);
set(a(i),'position',pos{i});
end
The point is that this code return only the last element.I mean,just the subplot(9,1,9).
How can I solve this ?
Thanks, Luiz

採用された回答

Ahmed A. Selman
Ahmed A. Selman 2013 年 4 月 10 日
It is a little tricky how loops are working in any program, aren't they? You used subplot and set and get within the same loop, this seems confusing matlab, and honestly I do not know exactly why. Also you calculated the values of (t) for 9 times.. which is needed only once.
So, try the code below, it may solve the problem:
clear
n=9;
pos=cell(1,n);
for d=8:-1:0
y(d+1)=0.045*d;
t=fliplr(y);
end
for i=1:n
a(i)=subplot(n,1,i);
pos{i}= get(a(i),'position');
end
for i=1:n
if i<9
set(gca,'xtick',[])
end
pos{i}(1,4)=(pos{i}(1,4))/2;
set(a(i),'position',pos{i});
pos{i}(1,2)=(pos{i}(1,2)) - t(i);
set(a(i),'position',pos{i});
end
  1 件のコメント
Luiz Felippe
Luiz Felippe 2013 年 4 月 10 日
Thank you so much

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with Phased Array System Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by