How can I put these subplots into a for loop?

4 次查看(过去 30 天)
Hello,
I have 1000 points of data (NumKey) I would like to divide into 10 different suplots each showing 100 points of the data. Every other data point is a random number which is why they are markered differently('*' being a random number). I started doing it manually, but am trying to figure out how to make it into a for loop.
I get a bit confused with nested for loops, so I would appreciate any advice.
Thank you in advance!
ntrials=1:100:1000;
figure;
subplot(10,1,1)
ntrials=1:numel(NumKey);
plot(ntrials(1:2:100),NumKey(1:2:100),'o');
hold on
plot(ntrials(2:2:100),NumKey(2:2:100),'*');
yticks([1 2 3 4]);
subplot(10,1,2)
ntrials=1:numel(NumKey);
plot(ntrials(101:2:200),NumKey(101:2:200),'o');
hold on
plot(ntrials(102:2:200),NumKey(102:2:200),'*');
yticks([1 2 3 4]);

采纳的回答

Geoff Hayes
Geoff Hayes 2019-2-26
Maria - for each of your two blocks of code, look at each line and ask yourself "what is different?" The part that is different will be controlled by your iterating parameter. The trick is finding the general term for the sequence (the part that is different for each of your subplots). In our case, the sequence is
code iteration code dependent upon k
============ ========= =========================
1:2:100 k = 1 ==> 1 + 0 * 100 : 2 : 1 * 100
101:2:200 k = 2 ==> 1 + 1 * 100 : 2 : 2 * 100
201:2:300 k = 3 ==> 1 + 2 * 100 : 2 : 3 : 100
...
k 1 + (k - 1) * 100 : 2 : k * 100
And so your code could become
ntrials=1:numel(NumKey);
for k = 1:10
subplot(10,1,k); % kth subplot
plot(ntrials((1 + (k-1)*100):2:k * 100), NumKey((1 + (k-1)*100):2:k * 100),'o');
hold on
plot(ntrials((2 + (k-1)*100):2:k * 100), NumKey((2 + (k-1)*100):2:k * 100),'*');
yticks([1 2 3 4]);
end
  1 个评论
Maria Y
Maria Y 2019-2-27
Hi Geoff,
Thanks so much for your detailed explanation. I'm very new to Matlab so having it broken down like that is very helpful. I"ll try to think of for loops in these terms going forward.
Thanks again!
Maria

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Axis Labels 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by