Plotting range of files using hold on in for loop

조회 수: 3 (최근 30일)
shedrach
shedrach 2025년 1월 6일
편집: KALYAN ACHARJYA 2025년 1월 6일
i have 3 groups of files in the same folder. i have selected them base on their index. i want to plot one file from each group on a figure using hold on. that is for each figure, i would have 3 plots with a total of three figures. I have my code like this below but it seems like i am getting only the last figure.
startIndex = 1;
endIndex = 3;
startIndex1 = 4;
endIndex1 = 6;
startIndex2 = 7;
endIndex2 = 9;
filelist = dir('C:\Users\shedr\Downloads\tec data\2017\DOBUM\ttr\ttr1\tt4\*.mat');
% filelistt = dir('C:\Users\shedr\Downloads\tec data\2017\DOBUM\ttr\ttr1\*.mat');
% first set of files
for fileidx = startIndex:endIndex
% count1 = count1+1;
spectrum = load(filelist(fileidx).name);
C = spectrum.B;
CC = cell2mat(C)
% second set of files
fileidx1 = startIndex1+(fileidx-startIndex)
% count2 = count2+1;
% count2 = count1
spectrum1 = load(filelist(fileidx1).name);
C1 = spectrum.B;
CC1 = cell2mat(C1)
fileidx2 = startIndex2+(fileidx-startIndex)
% count2 = count2+1;
% count2 = count1
spectrum2 = load(filelist(fileidx2).name);
C2 = spectrum.B;
CC2 = cell2mat(C2)
plot(CC, 'displayname', filelist(fileidx).name);
hold on
plot(CC1,'displayname', filelist(fileidx1).name);
hold on
plot(CC2,'displayname',filelist(fileidx2).name);
end
hold off
legend('show')

답변 (1개)

Cris LaPierre
Cris LaPierre 2025년 1월 6일
I think you need to add a figure command to your code. Otherwise, plot will overwrite the current figure.
startIndex = 1;
endIndex = 3;
startIndex1 = 4;
startIndex2 = 7;
filelist = dir('C:\Users\shedr\Downloads\tec data\2017\DOBUM\ttr\ttr1\tt4\*.mat');
% first set of files
for fileidx = startIndex:endIndex
spectrum = load(filelist(fileidx).name);
C = spectrum.B;
CC = cell2mat(C)
% second set of files
fileidx1 = startIndex1+(fileidx-startIndex)
spectrum1 = load(filelist(fileidx1).name);
C1 = spectrum.B;
CC1 = cell2mat(C1)
fileidx2 = startIndex2+(fileidx-startIndex)
spectrum2 = load(filelist(fileidx2).name);
C2 = spectrum.B;
CC2 = cell2mat(C2)
figure
plot(CC, 'displayname', filelist(fileidx).name);
hold on
plot(CC1,'displayname', filelist(fileidx1).name);
plot(CC2,'displayname',filelist(fileidx2).name);
hold off
legend('show')
end

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by