我正在使用MATLAB繪製圖表。任務是從FOR循環中的文件中讀取三個變量,讀取變量,繪製圖(1)(var1 vs var2),保存該圖,保存;情節圖(2)(var1 vs Var3)保存劇情保存它。打開另一個文件,讀取三個變量並在同一頁面上重複繪圖!現在在一個文件夾中有25個這樣的文件,它們將使用不同的顏色繪製,但在同一個繪圖上。就像在一個頁面上的所有var1和var2一樣。我的問題是給所有25個var1與var2的圖表傳說。我寫了一個示例代碼,但傳說沒有顯示。任何人都想幫助我解決問題!如何使用for循環和按住命令在matlab中使用圖例?
我的代碼如下:
clc
clear
close all
colormap jet;
%cmap=colormap;
cmap = [jet(2); jet(2)];
curve_legends1 = cell(25, 1);
curve_legends2 = cell(25, 1);
files=cellstr(ls('*.txt'));
for kk=1:length(files)
file1=files{kk};
[pathstr,name,ext] = fileparts(file1);
startRow = 2;
formatSpec = '%15s%15s%15s%15s%15s%15s%15s%15s%15s%15s%15s%15s%15s%15s%s%[^\n\r]';
%% Open the text file.
fileID = fopen(file1,'r');
dataArray = textscan(fileID, formatSpec, 'Delimiter', '', 'WhiteSpace', '', 'HeaderLines' ,startRow-1, 'ReturnOnError', false);
%% Close the text file.
fclose(fileID);
raw = repmat({''},length(dataArray{1}),length(dataArray)-1);
for col=1:length(dataArray)-1
raw(1:length(dataArray{col}),col) = dataArray{col};
end
numericData = NaN(size(dataArray{1},1),size(dataArray,2));
for col=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
% Converts strings in the input cell array to numbers. Replaced non-numeric
% strings with NaN.
rawData = dataArray{col};
for row=1:size(rawData, 1);
% Create a regular expression to detect and remove non-numeric prefixes and
% suffixes.
regexstr = '(?<prefix>.*?)(?<numbers>([-]*(\d+[\,]*)+[\.]{0,1}\d*[eEdD]{0,1}[-+]*\d*[i]{0,1})|([-]*(\d+[\,]*)*[\.]{1,1}\d+[eEdD]{0,1}[-+]*\d*[i]{0,1}))(?<suffix>.*)';
try
result = regexp(rawData{row}, regexstr, 'names');
numbers = result.numbers;
% Detected commas in non-thousand locations.
invalidThousandsSeparator = false;
if any(numbers==',');
thousandsRegExp = '^\d+?(\,\d{3})*\.{0,1}\d*$';
if isempty(regexp(thousandsRegExp, ',', 'once'));
numbers = NaN;
invalidThousandsSeparator = true;
end
end
% Convert numeric strings to numbers.
if ~invalidThousandsSeparator;
numbers = textscan(strrep(numbers, ',', ''), '%f');
numericData(row, col) = numbers{1};
raw{row, col} = numbers{1};
end
catch me
end
end
end
%% Replace non-numeric cells with NaN
R = cellfun(@(x) ~isnumeric(x) && ~islogical(x),raw); % Find non-numeric cells
raw(R) = {NaN}; % Replace non-numeric cells
data = cell2mat(raw);
alt = data(:, 1);
altkm = alt/1000
h2o = data(:, 2);
o2 = data(:, 3);
figure(1)
Plot_color=cmap(kk/1,:);
plot(h2o,altkm,'Color', Plot_color);
curve_legends1{kk+1} = ['LT = ' num2str(kk+1)];
ylim([0 110]);
hold on
s=[name];
ii=sscanf(s,'fig1_H2O_%f',[1,inf])'
saveas(gca,sprintf('fig1_H2O_%d.pdf',(ii)))
figure(2)
Plot_color=cmap(kk/1,:);
plot(o2,altkm,'Color', Plot_color);
curve_legends2{kk+1} = ['LT = ' num2str(kk+1)];
ylim([0 110]);
hold on
s=[name];
ii=sscanf(s,'fig2_O2S_%f',[1,inf])'
saveas(gca,sprintf('fig2_O2_%d.pdf',(ii)))
end
%% Clear temporary variables
clearvars filename startRow formatSpec fileID dataArray ans;
我會執行它會讓你知道! – MPJ