MATLAB 函数基础


基础


%% I. 清空环境变量及命令
clear all   % 清除Workspace中的所有变量
clc         % 清除Command Window中的所有命令

%% II. 变量命令规则
%%
% 1. 变量名区分大小写
A = 2
a = 3

%%
% 2. 变量名长度不超过63位
% ABCDEFGHIJKLMNOPQRSTUVWXYZ123456ABCDEFGHIJKLMNOPQRSTUVWXYZ123456 = 3

%%
% 3. 变量名以字母开头,可以由字母、数字和下划线组成,但不能使用标点
% 3A = 4
% .a = 5
% /b = 5
a_2 = 3
% a.2 = 4

%%
% 4. 变量名应简洁明了,通过变量名可以直观看出变量所表示的物理意义
A = rand(3,5)
rows = size(A, 1)
cols = size(A, 2)

%% III. MATLAB数据类型
%%
% 1. 数字
2 + 4
%%
% 2. 字符与字符串
s = 'a'
abs(s)%取绝对值
char(65)
num2str(65)

str = 'I Love MATLAB & Machine Learning.'

length(str)

doc num2str
%%
% 3. 矩阵
A = [1 2 3; 4 5 2; 3 2 7]
B = A'
C = A(:)%转换为列向量
D = inv(A)%求矩阵的逆矩阵
A * D

E = zeros(10,5,3)
E(:,:,1) = rand(10,5)
E(:,:,2) = randi(5, 10,5)
E(:,:,3) = randn(10,5)

%%
% 4. 元胞数组
A = cell(1, 6)
A{2} = eye(3)
A{5} = magic(5)
B = A{5}

%%
% 5. 结构体
books = struct('name',{{'Machine Learning','Data Mining'}},'price',[30 40])
books.name
books.name(1)
books.name{1}

%% IV. MATLAB矩阵操作
%%
% 1. 矩阵的定义与构造
A = [1 2 3 5 8 5 4 6]
B = 1:2:9
C = repmat(B, 3, 1)%复制矩阵
D = ones(2, 4)

%%
% 2. 矩阵的四则运算
A = [1 2 3 4; 5 6 7 8]
B = [1 1 2 2; 2 2 1 1]
C = A + B
D = A - B
E = A * B'
F = A .* B
G = A / B     % G * B = A     G * B * pinv(B) = A * pinv(B)    G = A * pinv(B)
H = A ./ B

%% 
% 3. 矩阵的下标
A = magic(5)
B = A(2,3)
C = A(3,:)
D = A(:,4)
[m, n] = find(A > 20)

%% V. MATLAB逻辑与流程控制
%%
% 1. if ... else ... end
A = rand(1,10)
limit = 0.75;

B = (A > limit);   % B is a vector of logical values
if any(B)
  fprintf('Indices of values > %4.2f: \n', limit);
  disp(find(B))
else
  disp('All values are below the limit.')
end

%%
% 2. for ... end
k = 10;
hilbert = zeros(k,k);      % Preallocate matrix

for m = 1:k
    for n = 1:k
        hilbert(m,n) = 1/(m+n -1);
    end
end
hilbert

%% 
% 3. while ... end
n = 1;
nFactorial = 1;
while nFactorial < 1e100
    n = n + 1;
    nFactorial = nFactorial * n;
end
n

factorial(69)
factorial(70)

prod(1:69)
prod(1:70)

%%
% 4. switch ... case ... end
mynumber = input('Enter a number:');
switch mynumber
    case -1
        disp('negative one');
    case 0
        disp('zero');
    case 1
        disp('positive one');
    otherwise
        disp('other value');
end

%% VI. MATLAB脚本与函数文件
%%
% 1. 脚本文件
myScript
%%
% 2. 函数文件
mynumber = input('Enter a number:');
output = myFunction(mynumber)

%% VII. MATLAB基本绘图操作
%%
% 1. 二维平面绘图
x = 0:0.01:2*pi;
y = sin(x);
figure
plot(x, y)
title('y = sin(x)')
xlabel('x')
ylabel('sin(x)')
xlim([0 2*pi])%限定X 轴取值范围

x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
figure
[AX,H1,H2] = plotyy(x,y1,x,y2,'plot');%公用横坐标函数
set(get(AX(1),'Ylabel'),'String','Slow Decay') 
set(get(AX(2),'Ylabel'),'String','Fast Decay') 
xlabel('Time (\musec)') 
title('Multiple Decay Rates') 
set(H1,'LineStyle','--')%设置线型
set(H2,'LineStyle',':')

%%
% 2. 三维立体绘图
t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t)
xlabel('sin(t)')
ylabel('cos(t)')
zlabel('t')
grid on
axis square

%%
% 3. 图形的保存与导出

% (1) Edit → Copy Figure
% (2) Toolbar → Save
% (3) print('-depsc','-tiff','-r300','picture1')
% (4) File → Export Setup

%% VIII. MATLAB文件导入
%%
% 1. mat格式
save data.mat x y1 y2
clear all
load data.mat

%%
% 2. txt格式
M = importdata('myfile.txt');%导入数据

S = M.data;
save 'data.txt' S -ascii
T = load('data.txt');

isequal(S, T)% 判断是否相等

%%
% 3. xls格式
xlswrite('data.xls',S)
W = xlsread('data.xls');
isequal(S, W)

xlswrite('data.xlsx',S)
U = xlsread('data.xlsx');
isequal(S, U)

%% 
% 4. csv格式
csvwrite('data.csv',S)
V = csvread('data.csv');
isequal(S, V)
%%

高级基础


%% I. 清空环境变量及命令
% clear all
clc
%% II. MATLAB编程习惯与风格
    x_coordinate = rand(1,10);
    y_coordinate = rand(1,10);
    figure
    plot(x_coordinate,y_coordinate,'r-*')
%% III. MATLAB程序调试
% %%
% % 1. Index must be a positive integer or logical.
% A = [1 2 3 4 5];
% A(0)
% A(3.5)
% A(-2)
% 
% %%
% % 2. Undefined function or variable 'B'.
% B
% 
% %%
% % 3. Inner matrix dimensions must agree.
% B = [1 2 3];
% A * B
% 
% %%
% % 4. Function definitions are not permitted at the prompt or in scripts.
% function c = add(a,b)
% c = a + b;
% 
% %%
% % 5. Index out of bounds because numel(A)=5.
% A(6)
% 
% %%
% % 6. In an assignment  A(I) = B, the number of elements in B and I must be the same.
% A(3) = B;
% 
% %%
% % 7. Expression or statement is incorrect--possibly unbalanced (, {, or [.
% mean(A(1:3)
% 
% %%
% % 8. Too many input arguments.
% mean(A,1,2)

%%
% 9. 循环体的调试
a = 1:100;
b = [];
for i = 21:21
    index = 105 - 5*i + 1;
    b = [b a(index)];
end

%%
% 10. 查看、编辑MATLAB自带的工具箱函数
edit mean

edit newff

%% III. MATLAB内存优化配置
feature memstats
% 
%% IV. 向量化编程
%%
% 1. 及时清除不用的变量
a = rand(10000);
b = rand(10000);
clear a
b = rand(10000);

%%
% 2. 使用变量前,预分配内存空间
clear all
clc
n = 30000;
tic;
for k = 1:n
    a(k) = 1;
end
time = toc;
disp(['未预分配内存下动态赋值长为',num2str(n),'的数组时间是:',num2str(time),'秒!'])

tic
b = zeros(1,n);
for k = 1:n
    b(k) = 1;
end
time = toc;
disp(['预分配内存下动态赋值长为',num2str(n),'的数组时间是:',num2str(time),'秒!'])

%%c
% 3. 选择恰当的数据类型
clear all
clc
n = 300000;
a = 8;
b{1} = 8;
c.data = 8;

tic
for k = 1:n;
    a;
end
time = toc;
disp(['访问',num2str(n),'次double型数组时间是:',num2str(time),'秒!'])

tic
for k = 1:n;
    b{1};
end
time = toc;
disp(['访问',num2str(n),'次cell型数组时间是:',num2str(time),'秒!'])

tic
for k = 1:n;
    c.data;
end
time = toc;
disp(['访问',num2str(n),'次struct型数组时间是:',num2str(time),'秒!'])

%% 循环与向量化
% 4. 按列优先循环
clear all
clc
n = 1000;
a = rand(n);
tic
for i = 1:n
    for j = 1:n
        a(i,j);
    end
end
toc

for i = 1:n
    for j = 1:n
        a(j,i);
    end
end
toc

%%
% 5. 循环次数多的变量安排在内层
clear all
clc
tic
a = 0;
for i = 1:1000
    for j = 50000
        a = a + 1;
    end
end
toc

tic
a = 0;
for i = 1:50000
    for j = 1:1000
        a = a + 1;
    end
end
toc

%%
% 6. 给一些函数“瘦身”
edit mean
clear all
clc
a = rand(1,10000);
tic
b = mean(a)
toc

tic
c = sum(a)/length(a)
toc

%% V. 图像对象和句柄
%%
% 1. 如何设置线条的属性呢?
x = 0:0.01:2*pi;
y = sin(x);
h = plot(x,y);
grid on
get(h)
set(h,'linestyle','-','linewidth',2,'color','k')

%%
% 2. 如何修改网格的间隔呢?  
set(gca,'xtick',0:0.5:7)
set(gca,'ytick',-1:0.1:1)

%%
% 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')

画图函数


clc;clear;close all;

[X,Y]=meshgrid(-2:0.1:2,-2:0.1:2);

Z=exp(-X.^2-Y.^2);

mesh(X,Y,Z);     %线框图

figure();

surf(X,Y,Z);     %表面图    % shading interp;

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值