Matlab使用技巧

来源:互联网 发布:java类库手册 编辑:程序博客网 时间:2024/04/29 17:23

    原文地址:http://blog.csdn.net/lqhbupt/article/details/20292113


(1) Matlab强制退出正在运行的程序
A: Ctrl + C
(2)如何让Matlab跑完程序后自动关机?
A: 在程序的末尾加上一条代码:
    system('shutdown -s')
   当然,记得在这条语句前加上保存结果的save,不然跑了很久的程序就白跑了。
 

(3) Matlab创建文件夹实例
A:  help exist查看下exist函数的用法
    示例: if exist('results')~=7
            mkdir('result')
          end
(4) Matlab中使用动态变量名
A: 编写程序时经常会遇到处理大量数据文件的情况,数据文件的命名比较相似,以一系列编号区分,如“a1.mat,a2.mat,... ,a100.mat " (假设其中的数据名称也为a1...a100) 。为了可以批量处理这些文件,可以采用如下的方法:
   for i=1:1:100
       s=strcat('a', int2Str(i));
       load(strcat(s,'.mat'));
       x=eval(s); %将数据a1赋值给x,便于后继统一处理
       % ...          %统一处理程序   
   end
为动态变量名赋值示例

   for i=1:10
       eval(['A',num2str(i),'=rand(1,i)']);
   end
动态调用A1~A10
可以使用cell数组,因为A1-A10是长度不同的向量。
   for i=1:10
       B{i}=eval(['A',num2str(i)]);
   end
(5) 通过命令行运行matlab带参函数
在命令行输入
   matlab -r "functionanme firstpara secondpara"
注意事项:引号不能少;functionname不包含「.m」后缀
(6) 怎么判定一个文件或者文件夹是否存在
if isequal(exist(filename,'file'),2)   %2 means it's a file
if isequal(exist(pathname,'dir'),7)    %7 means it's a directory
(7)Matlab中用图片制作小电影
方法:使用VideoWriter()类
%% Movie Test.
%% Set up some function. 
% Sine between -2*pi and 2*pi.
x = (10*-pi:0.1:10*pi)'; % Note the transpose.
y = sin(x);
fid = figure;
hold on
% The final plot.
plot(x,y, '*'); 
%% Set up the movie.
writerObj = VideoWriter('out.avi'); % Name it.
writerObj.FrameRate = 60; % How many frames per second.
open(writerObj);  
for i=1:size(y)      
    % We just use pause but pretend you have some really complicated thing here...
    pause(0.1);
    figure(fid); % Makes sure you use your desired frame.
    plot(x(i),y(i),'or'); 
    %if mod(i,4)==0, % Uncomment to take 1 out of every 4 frames.
        frame = getframe(gcf); % 'gcf' can handle if you zoom in to take a movie.
        writeVideo(writerObj, frame);
    %end 
end
hold off
close(writerObj); % Saves the movie.
(8) Matlab计算L2欧氏距离
Matlab内置函数pdist2(p1,p2,'euclidean')
可以计算一个点和一组点的距离。示例:
% Define our points.
aPoint = [1,4]; % A single point with 2 components.
bunchOfPoints = [2,3; 1,4; 0,1]; % A bunch of other points. 
d = pdist2(aPoint,bunchOfPoints,'euclidean') 
(9) Matlab如何计算均方误差root-mean-square-error
函数rms
% The actual values that we want to predict.
Actual = [1 2 3 4]; 
% The values we actually predicted.
Predicted = [1 3 1 4]; 
% One way is to use the Root Mean Square function and pass in the "error" part.
rmse = rms(Predicted-Actual)
(10) Matlab计算平均绝对误差mean-absolute-error

函数mae
% The actual values.
Actual = [1 2 3 4]; 
% The values we predicted.
Predicted = [1 3 1 4];  
% You can just use the built in Mean Absolute Error function and pass in the "error" part.
builtInMAE = mae(Actual-Predicted)
(11) Matlab内置Random Forest算法

% Train the TreeBagger (Decision Forest).

nTrees = 20;
B = TreeBagger(nTrees,traindata,trainlabels, 'Method', 'classification');
predChar = B.predict(testdata);
predClass = str2double(predChar)

(12) 为图像中的部分pixel上色
源图像origImg; binary 图像maskImg其中0代表背景,1代表要上色的点。
%% Example on how to color select pixels in an image.
% The original COLOR image.
origImg = imread('ngc6543a.jpg');
 
% Make sure the values are within 0-255.
origImg = uint8(origImg);
 
% View the original image.
figure; fId = imagesc(origImg); axis image;
title('click and hold mouse to draw on the original image'); 
 
% The user draws on the image to select the pixels to highlight.
M = imfreehand();
 
% 0 = background pixels (do not change).
% 1 = foreground pixels (change these colors).
maskImg = M.createMask;
 
% View the black and white mask.
figure; imagesc(maskImg); colormap gray; axis image;
 
% Now let's color the mask green to make it more interesting. 
% To do this, we have to make three matrices, one for each color channel.
 
% Increase the color by half the max value so we can see some transparancy 
% in the original image.
amountIncrease = 255/2;
 
alphaImg(:,:,1) = zeros(size(maskImg)); % All zeros.
alphaImg(:,:,2) = round(maskImg*(amountIncrease)); % Round since we're dealing with integers.
alphaImg(:,:,3) = zeros(size(maskImg)); % All zeros. 
 
% Convert alphaImg to have the same range of values (0-255) as the origImg.
alphaImg = uint8(alphaImg);
 
% View alphaImg.
figure; imagesc(alphaImg); axis image;
 
% Combine the original images and the alpha values to highlight the select
% pixels.
blendImg = origImg + alphaImg;
 
% Show the blended images.
figure; imagesc(blendImg); axis image;
(13) print图片打印
print -fhandle -rresolution -dfileformat filename
例如print -f2 -r300 -djpeg myfigure命令将句柄为2的图像生成myfigure.jpg文件,分辨率为dpi300
如果要求矢量图,可以用-depsc 
如果要批量制图,参考如下循环流程
for kk = 1:10
%%%生成图像
% 如果需要调整图像大小
% 在存储前使用
% set(handle,'Position',[left, bottom, width, height])
% 例如 set(gca, 'Position',[80,100,800,600])
...
print('-r150','-depsc',['d:\image\myfigure',sprintf('%02d',kk)])
end
print 调整图像大小的命令
默认状态下打印大小为[0.25 2.5 8.0 6.0] in inches
调整命令三行连用
set(gcf, 'PaperPositionMode', 'manual');
set(gcf, 'PaperUnits', 'inches');
set(gcf, 'PaperPosition', [2 1 4 2]);
units: inches,centimeters, normalized, points
(14) print命令保存eps文件与figure文件显示不同之解决方法
在print('-depsc','a.eps');一句前加上 "set(gcf,'paperpositionmode','auto');"  即可


0 0
原创粉丝点击