??最近做了一個(gè)matlab實(shí)驗(yàn)任務(wù)荡陷,主要是將數(shù)據(jù)文檔中的數(shù)據(jù)進(jìn)行處理雨效。考慮到數(shù)據(jù)文件的保密性废赞,本文就簡單介紹一下實(shí)驗(yàn)中用到的函數(shù)和語法徽龟。
實(shí)驗(yàn)數(shù)據(jù)以及實(shí)驗(yàn)?zāi)康?/h3>
??新建了一個(gè)數(shù)據(jù)文件data.txt,文件內(nèi)容主要包括最小value(第一行)蛹头;方案組合(color顿肺,size戏溺,length);表頭(run no., number, value);以及具體的數(shù)字屠尊。
-run no.——運(yùn)行次數(shù)序號(hào)旷祸,每個(gè)組合運(yùn)行五次;
-number——每次運(yùn)行中第一次達(dá)到最優(yōu)值的迭代次數(shù)讼昆;
-value——運(yùn)行得到的最優(yōu)值托享;
??本次實(shí)驗(yàn)的目的是得到每個(gè)組合中達(dá)最優(yōu)值(最小值 456.7)的迭代次數(shù)的最小值、最大值浸赫、均值以及方差闰围。
代碼實(shí)現(xiàn)
1. matlab讀取文件,并輸出“The minimal is 456.7”
%% 讀取數(shù)據(jù)
fid = fopen('matlab實(shí)驗(yàn)-簡書\data.txt','r+');
FormatString=repmat('%s',1,3);
A=textscan(fid,FormatString,1,'HeaderLines',0);
A1=A{1};
A2=cell2mat(A1);
formatSpec ='The minimal is %s.\n';
fprintf(formatSpec,A2)
2. 輸出列名
%% 輸出列名
s1=' ';
num=' num';
m1=' min';
m2=' max';
m3=' mean';
fdev=' fdev';
fprintf('%s %s %s %s %s %s\n',s1,num,m1,m2,m3,fdev);
3. 處理行名及數(shù)據(jù)內(nèi)容
%% 處理行名及求數(shù)據(jù)
for x=1:7:14
%處理行名既峡,將組合名稱縮寫
fid = fopen('matlab實(shí)驗(yàn)-簡書\data.txt','r+');
B=textscan(fid,FormatString,1,'HeaderLines',x);%從文件的第x行開始取數(shù)據(jù)羡榴,取1行數(shù)據(jù)
B1=B{1};
B2=cell2mat(B1);
line_short=strrep(B2,'red','re');
line_short=strrep(line_short,'blue','bl');
line_short=strrep(line_short,'big','bi');
line_short=strrep(line_short,'small','sm');
line_short=strrep(line_short,'long','lo');
line_short=strrep(line_short,'short','sh');
%
C=textscan(fid,FormatString,5,'Headerlines',2);%接上面的B,從第x行后的第二行(x+2行)開始取數(shù)據(jù),取5行
C1=C{3};
C1C=C{2};
C2=cell2mat(C1);
%將每個(gè)組合運(yùn)行5次中達(dá)到最小值的number放進(jìn)矩陣
C3=string(C2);
C4=vpa(C3,6);
C5=string(A2);
i=1;
xx=strings;
for y=1:5
if (C3(y)==C5)
yy=C1C{y};
xx(i)=yy;
i=i+1;
end
end
C6=double(xx);
le=length(C6(:));
count=le;
%計(jì)算每個(gè)組合5次運(yùn)行中達(dá)到最小值的number的最小值运敢、最大值校仑、均值
data_min=min(C6(:));
data_max=max(C6(:));
C9=mean(C6(:));
data_mean=vpa(C9,4);
C11=0;
%計(jì)算方差
for j=1:le
C11=C11+(C6(j)-C9)^2;
end
C12=C11./(le-1);
data_fdev=vpa(C12,6);
%打印數(shù)據(jù)
fprintf('%s:%6.0f %6.0f %6.0f %7.0f %13.3f\n',line_short,count,data_min,data_max,data_mean,data_fdev);
fclose(fid);
end
代碼結(jié)果
最終的實(shí)驗(yàn)結(jié)果如下:
注:
??本次實(shí)驗(yàn)代碼不嚴(yán)謹(jǐn),只是保證結(jié)果運(yùn)行策略传惠,沒有進(jìn)行規(guī)范化書寫迄沫,畢竟只是個(gè)作業(yè)哈~