How to run this code in a for loop?
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi all!
I have a code that requires to go to the folder, calls mat files and then plot images. I want to run everything in a for loop. Could you please tell me how can I do this? The individual code is like this -
%% Day 01
cd(strcat('/Users/aahmed78/PhD/Data/Day26/Two Particle'));
load('Day01_Path.mat');
Leng = numel(t);
plot(p0_x,p0_y);
for i = 1:Leng
figure(1); hold on;
title('26-April-2015 to 02-May-2015','fontsize',20);
plot(px(i,:),py(i,:),'o','MarkerSize',2,'color',[0 1 0]);
end
hold on;
%% Day 02
cd(strcat('/Users/aahmed78/PhD/Data/SWOT/Day27/Two Particle'));
load('Day02_Path.mat');
Leng = numel(t);
plot(p0_x,p0_y);
for i = 1:Leng
figure(1); hold on;
title('26-April-2015 to 02-May-2015','fontsize',20);
plot(px(i,:),py(i,:),'o','MarkerSize',2,'color',[0 1 0]);
end
hold on;
%% Day 03
cd(strcat('/Users/aahmed78/PhD/Data/SWOT/Day28/Two Particle'));
load('Day03_Path.mat');
Leng = numel(t);
plot(p0_x,p0_y);
for i = 1:Leng
figure(1); hold on;
title('26-April-2015 to 02-May-2015','fontsize',20);
plot(px(i,:),py(i,:),'o','MarkerSize',2,'color',[0 1 0]);
end
hold on;
an so on for the 7 days. Please note that the folders name are Day26, Day27, Day28, ..., Day32. But the .mat file that I call is Day01, Day02, ... ,Day07. Rest of the codes are the same. I wrote down this code to solve -
for k = 1:7
cd(strcat('/Users/aahmed78/PhD/Data/Day',num2str(day(k+26)),'/Two Particle'));
load('Day0',num2str(day),'_Path.mat');
Leng = numel(t);
plot(p0_x,p0_y); hold on;
for i = 1:Leng
figure(1); hold on;
title('26-April-2015 to 02-May-2015','fontsize',25);
plot(px(i,:),py(i,:),'o','MarkerSize',2);
hold on;
end
hold on;
end
But it is showing me
Index exceeds the number of array elements (1).
Any feedback from you guys will be much appreciated!
댓글 수: 0
채택된 답변
Raymond Norris
2022년 4월 15일
You don't provide the line number of the error. What is day? Is that they time function? Couldn't
day(k+26)
be written as just
k+26
And then
load('Day0',num2str(day),'_Path.mat');
would be
load('Day0',num2str(k),'_Path.mat');
Secondly, you ought to be able to vectorize your inner for-loop to a single call to plot. Your call to load is missing a concatenation. You left off the color for plotting px/py. Try the following
hold on
for k = 1:7
cd(strcat('/Users/aahmed78/PhD/Data/Day',num2str(k+26),'/Two Particle'))
load(['Day0',num2str(k),'_Path.mat'])
plot(p0_x,p0_y)
plot(px,py,'o','MarkerSize',2,'color',[0 1 0])
end
title('26-April-2015 to 02-May-2015','fontsize',25)
hold off
댓글 수: 2
Rik
2022년 4월 15일
You should load to a variable, and you probably want to use sprintf to compose the file name.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!