存在宇宙之中 长在地球之上分享 http://blog.sciencenet.cn/u/wangchangzai

博文

matlab笔记

已有 7918 次阅读 2009-12-25 18:08 |个人分类:生活点滴|系统分类:科研笔记| 写文件, 读文件

matlab中写txt文件
filename =['ts2b.txt'];  % input file
fid = fopen(filename);  %open the input file
 
%如果按行读取,并显示
while 1
nextline = fgetl(fid); %读取下一行
disp(nextline);
if ~isstr(nextline), break, end %如果到文件尾,结束
end
 

%跳过N行
N = 6;
for i=1:N
nextline = fgetl(fid); %读取下一行
if ~isstr(nextline), break, end %如果到文件尾,结束
end
 
%读取某行的内容,转换为字符,或者是浮点数
nextline = fgetl(fid); %再读一行
line_content =textscan(nextline,'%s');
%line_content 的引用为 line_content{1,1}(1)

%如果数据是成块的,则可以一次读入整块数据
cols = 4;
rows = 10;
data   fscanf(fid,'%f',[cols rows]);
matlab中写txt文件

Varabel1 ={'ID';'Score'};

Varabel2 = [1 10

2 30

3 50];

%Varabel1, Varabel2, just as example input 

 

fidout=fopen('out.txt','w');  %打开一个文件,可写 
[row1 col1] = size(Varabel1);  %NmsOut,STTCum 为两个变量
[row2 col2] = size(Varabel2);  %取得两个变量的行和列
%Varabel1存取的是 列名
%Varabel2中存取的是各列的内容
%先将列名写入文件,可用空格或逗号分开,最后一个列名输入后回车
fprintf(fidout,'%s    ,',Varabel1{1:row1-1,1});
fprintf(fidout,'%sn',Varabel1{row1,1});

%对每一行的内容重复操作
for i=1:row2
    fprintf(fidout,'%f    ,',Varabel2(i,1:col2-1));  
    fprintf(fidout,'%fn',Varabel2(i,col2));  
end
%这样输出的文件,可以用excel打开。

matlab中如何修改坐标Label的位置和内容

x = 1:100;
y = sin(x);
plot(x,y);  %画曲线
Xtick_pos = x(1:length(x)/10:length(x));
%或者可以写为  Xtick_pos = [0 20 50 100];
%确定label显示的位置

Xtick_label = x(1:length(x)/10:length(x));
%或者可以写为 Xtick_label  ={'a','b','c','d'};

set(gca,  'XTickLabel',Xtick_label, 'XTick',Xtick_pos);
%此命令替换了横坐标label的内容

matlab的一些小技巧(1)

1. 注释掉一段程序:%

可以选中要注释内容,在右键菜单中选择Comment (Uncomment去掉注释标记),或使用快捷键Ctrl+R。将光标放在需要注释的行中,按Ctrl+R,将该行变为注释。取消注释也是一样的,快捷键为Ctrl+T。

2. cell模式
在一个长长的脚本m文件中,可能需要对其中的一段反复修改,查看执行效果,这时,cell模式就非常有用了。cell模式相当于将其中的代码拷贝到命令窗口中运行。两个%后接一个空格(%% )开始一个cell。当然,也可以在菜单Cell-> Insert Cell Divider中加入一个cell.

将输入光标放到一个cell中时,背景将变为浅黄色,Ctrl+Enter执行cell中的代码。
执行cell中代码时不需要保存m文件,该m文件可以不在路径列表中。
cell模式中,断点不起作用,当然,调用的子程序中的断点还是正常的。

3.  写m文件时,选中某段程序内容,ctrl+i 让matlab帮你自动对齐程序。这样程序看起来很有层次,容易发现程序中的错误。

Matlab读未知大小文件的方法

有些文件,你只知道里面数据存放的格式,而不知道数据的多少。
如有如下文件data.txt,一列存放:
0.99000
1.99000
2.99000
3.99000
4.99000
5.99000
6.99000
读文件前,数据的行数未知,这样就需要一行一行读,然后判断是否到了文件尾。
例程如下:
filename = 'data.txt'
fid = fopen(filename,'r');  % 打开文件,只读
if fid==-1
    disp('File does not exist'); %如果打开失败
end
rownmb = 0;  %记录行数
nextline = fgetl(fid);  %读取一行
while isstr(nextline)    %判断是否为文件尾
    rownmb = rownmb +1;  %行数加1
    line_content =textscan(nextline,'%f'); %获取这一行的内容,%f控制读取数据的格式
    data(rownmb,1) = line_content{1,1}(1); %存取数据
    nextline = fgetl(fid); %read next line
end

sta=fclose(fid);  %关闭文件
if sta == -1  
    disp('File not cloed');
end

如果读取的文件为二进制,例程如下:
filename = 'data.bin';     %二进制文件,不一定以bin做后缀,主要看存储时候的方法  
fid = fopen(filename,'r');  % open the file
if fid==-1
    disp('File does not exist');
end
rownmb = 0;

while 1
    temp = fread(fid,1,'double');  %读取一个数据
    if feof(fid)      %判断是否为文件尾,如果是,结束
        break;        %即使是到了文件尾,还依然可以用fread读取,只不过读取结果为空[]
    end
    rownmb =  rownmb + 1;  %如果还不是文件尾,行数加1
    data(rownmb,1) = temp;  %存取数据
end

sta=fclose(fid);  %关闭文件
if sta == -1
    disp('File not cloed');
end

sta=fclose(fid);
if sta == -1
    disp('File not cloed');
end

matlab中图形的简单裁剪处理

MATLAB定义的NaN常数可以用于表示那些不可使用的数据,利用这种特性,可以将图形中需要裁剪部分对应的函数值设置成NaN,这样在绘制图形时,函数值为NaN的部分将不显示出来,从而达到对图形进行裁剪的目的。
例子:
x=0:0.1:2*pi;  %定义x向量
[x,y]=meshgrid(x); %创建网格,y=x
z=sin(y).*cos(x);   %定义z变量
[I,J]=find(z>0.25);  %将z>0.25部分设置为NaN
for ii=1:length(I)
  z(I(ii),J(ii))=NaN;
end
surf(x,y,z);

%最终效果就是:三维曲面图中z>0.25部分被裁减掉了。

matlab提速技巧(自matlab帮助文件)

1.首先要学会用profiler.
1.1. 打开profiler.
To open the Profiler, select View -> Profiler from the MATLAB desktop, or type profile viewer in the Command Window. The MATLAB Profiler opens.
在我的机器上是: 在matlab desktop下,Desktop->Profiler.
在M文件编辑器下,Tools->Open Profiler.
1.2. 运行profiler
可以把要运行的code拷入Run this code后面的输入框里。
You can run this example
[t,y] = ode23('lotka',[0 2],[20;20])
也可以输入要运行的M文件名。
1.3.Click Start Profiling (or press Enter after entering the statement).
1.4. 查看Profile Detail Report
会告知你哪些代码消耗了多少时间,可以找到哪些函数或那些代码行消耗了主要的时间,或者是经常被调用。

也可以用stopwatch Timer函数,计算程序消耗时间
Use tic and toc as shown here.
tic
   - run the program section to be timed -
toc


2. 加速1:向量化
MATLAB is a matrix language, which means it is designed for vector and matrix operations. You can often speed up your M-file code by using vectorizing algorithms that take advantage of this design. Vectorization means converting for and while loops to equivalent vector or matrix operations.

i = 0;
for t = 0:.01:1000
    i = i+1;
    y(i) = sin(t);
end

运行时间为30.776秒。
改为向量化代码:
t = 0:.01:1000;
y = sin(t);
运行时间为0秒。

Functions Used in Vectorizing
Some of the most commonly used functions for vectorizing are:
 
all
 diff
 ipermute
 permute
 reshape
 squeeze
 any
 find
 logical
 prod
 shiftdim
 sub2ind
 cumsum
 ind2sub
 ndgrid
 repmat
 sort
 sum
 
 3.
加速2:Preallocating Arrays(预分配空间)
You can often improve code execution time by preallocating the arrays that store output results. Preallocation makes it unnecessary for MATLAB to resize an array each time you enlarge it. Use the appropriate preallocation function for the kind of array you are working with.
Preallocation also helps reduce memory fragmentation if you work with large matrices.

4.加速其他方法:
Coding Loops in a MEX-File for Speed

If there are instances where you must use a for loop, consider coding the loop in a MEX-file. In this way, the loop executes much more quickly since the instructions in the loop do not have to be interpreted each time they execute.

Functions Are Faster Than Scripts

Your code will execute more quickly if it is implemented in a function rather than a script. Every time a script is used in MATLAB, it is loaded into memory and uated one line at a time. Functions, on the other hand, are compiled into pseudo-code and loaded into memory once. Therefore, additional calls to the function are faster.

Load and Save Are Faster Than File I/O Functions

If you have a choice of whether to use load and save instead of the MATLAB file I/O routines, choose the former. The load and save functions are optimized to run faster and reduce memory fragmentation.

Avoid Large Background Processes

Avoid running large processes in the background at the same time you are executing your program in MATLAB. This frees more CPU time for your MATLAB session.

 

 5. 多线程
在matlab desktop里,File->Preferences->General->Multithreading, 看是否选择了Enable Multithreaded Computation。

如果没选,check it, 看是否有提速

均引用与http://blog.sina.com.cn/s/articlelist_1636495765_1_1.html


https://blog.sciencenet.cn/blog-295036-281400.html

上一篇:matlab colormap详解
下一篇:一个非英语专业的人的自述:我如何用一年时间考上欧盟口译司
收藏 IP: .*| 热度|

0

发表评论 评论 (1 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-23 18:01

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部