matlab注意事项
矩阵的下标是从1开始,不是0,且不支持关联数组,当数组下标是字符或字符串时,会被转成ASCII码;
matlab相关概念
%% 清空环境变量命令
clear all %清除Workspace中的所有变量;
clc %清除Command Window中所有命令
% CTRL+R 注释多行代码 CTRL+T反注释
% 加分号就是不把该行的结果在matlab的窗口中显示出来,不加就是显示
pikaqiu = 111
% 获取变量的行数和列数
num = rand(5,6)
rows = size(num , 1) %rows = 5;
cols = size(num , 2) %cols = 6;
% 字符串
str1 = 'a' % 不区分字符和字符串,一行只能定义一个变量
str2 = 'pikaqiu'
% 矩阵
arr = [1 2 3 ; 4 5 6] %行元素这间的分隔符不用空格,用,号也可以
arrs = zeros(3,5,2) %定义了2个3*5的矩阵,初始值增均为0
arrs(: , : , 1) = rand(3,5) %给第一个矩阵赋值
arr_double = cell(2 ,3) %元胞数组,多维数组
% 结构体
pikaqiu_group = struct('name' , {{'pikaqiu1', 'pikaqiu2'}} , 'age' , [2,3])
%matlab的文件分为两类,脚本文件和函数文件,其中脚本文件可以直接执行,
%但函数文件必须有一个输入才能执行图形绘制
%% 基本绘图操作
% 二维平面绘图
x = 0:0.01:2*pi; %图形取值范围
y = sin(x); %图形的函数
figure %使用默认参数图形窗口创建
plot(x, y) %绘制图形
title('y = sin(x)') %图形标题
xlabel('x') %图形x轴标签
ylabel('sin(x)') %图形y轴标签
xlim([0 2*pi]) %图形取值范围限定
%三维绘图
t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t)
xlabel('sin(t)')
ylabel('cos(t)')
zlabel('t')
grid on
axis square
% 形的保存与导出
% (1) Edit → Copy Figure
% (2) Toolbar → Save
% (3) print('-depsc','-tiff','-r300','picture1')
% (4) File → Export Setup
%文件导入
%mat格式
save data.mat x y1 y2 %变量保存
clear all
load data.mat
%txt格式
M = importdata('myfile.txt');
S = M.data;
save 'data.txt' S -ascii
T = load('data.txt');
isequal(S, T)
%xls格式
xlswrite('data.xls',S)
W = xlsread('data.xls');
isequal(S, W) %S和W的数据校验,结果为1时相等
xlswrite('data.xlsx',S)
U = xlsread('data.xlsx');
isequal(S, U)
%csv格式
csvwrite('data.csv',S)
V = csvread('data.csv');
isequal(S, V)matlab常用操作
%% 代码调试
% 断点模式,代码所在行前单击设置断点,再次单击取消,F10下一个断点
% 循环体的调试
a = 1:100;
b = [];
for i = 1:21
index = 105 - 5*i;
% b = [b a(index)];
end
% 查看、编辑matlab自带的函数
edit mean %查看matlab自带的求平均值的函数
%matlab内存优化
feature memstats %查看内存使用情况
% 预分配内存
n = 50000;
tic %开启定时器
b = zeros(1,n); %预分布内存
time = toc; %获取执行时间
% 未预分配内存下动态赋值长为3000000的数组时间是:0.52041秒!
% 预分配内存下动态赋值长为3000000的数组时间是:0.075799秒!
% 预分配内存在n的数量级很大时,时间上少一个数量级,当n的数量级不大时,则无明显区别
% 嵌套循环时,循环次数大的尽量放在内层
% 清除变量,释放内存
a = rand(10000);
clear a
%% V. 图像对象和句柄
%%
% 1. 如何设置线条的属性呢?
x = 0:0.01:2*pi;
y = sin(x);
h = plot(x,y);
grid on
get(h)
set(h,'linestyle',':','linewidth',5,'color','b')
%%
% 2. 如何修改网格的间隔呢?
set(gca,'xtick',0:0.5:7)
%%
% 3. 如何设置图例的字体及大小呢?
x = 0:0.01:2*pi;
y1 = sin(x);
y2 = cos(x);
plot(x,y1,'r')
hold on
plot(x,y2,'-.b')
h = legend('sin(x)','cos(x)');
set(h,'fontsize',16,'color','k','edgecolor','r','textcolor','w')
%%
% 4. 如何拆分图例呢?
x = 0:0.01:2*pi;
y1 = sin(x);
y2 = cos(x);
h1 = plot(x,y1,'r');
hold on
h2 = plot(x,y2,'-.b');
ax1 = axes('position',get(gca,'position'),'visible','off');
legend(ax1,h1,'sin(x)','location','northwest')
ax2 = axes('position',get(gca,'position'),'visible','off');
legend(ax2,h2,'cos(x)','location','northeast')