文章目录
- Matlab学习记录
- 使用帮助文档
- Matlab读取CSV文件
- MATLAB查看变量的类型
- Matlab 提取矩阵 某一行 或者 某一列 的方法
- mic的计算
- 矩阵下标从1开始
- 矩阵转置
- 获取向量、矩阵行数、列数
- 排序 sort
- 如何找到一个数组中的最大值以及它所在的位置
- Matlab中怎样写函数求数组中最大K个值的下标
- 判断矩阵是否存在某元素
- 判断矩阵中某元素是否相等
- 统计矩阵中某元素的数目
- find()函数基本功能
- 结构体数组
- 如何生成一个集合的所有子集
- 怎么从一个向量中去掉一个元素
- 数 + 向量 ==> 向量
- fullBNT 函数learn_struct_mcmc.m
- causal_explorer toolkit
- matlab中的addpath用法
- MATLAB中load函数的用法
- 求两个集合的 交集 和 并集
- 稀疏矩阵问题
- DAG的构建,无环性检查
- 打印输出显示
- 随机数
- repmat 重复数组副本
- 矩阵点乘
- 时间
- 文件读写
- .m文件批量转换为 .p 文件
- matlab程序打包
- 画图
Matlab学习记录
最近准备使用matlab做贝叶斯网络方面的工作,matlab是第一次用,就遇到的问题进行记录。
使用帮助文档
Matlab读取CSV文件
MATLAB查看变量的类型
>> a = 100;
>> class(a)
int
Matlab 提取矩阵 某一行 或者 某一列 的方法
A(i,:) % 提取矩阵A的第 i行
A(:,i) % 提取矩阵A的第 i列
mic的计算
mine(a,b)
矩阵下标从1开始
>> data(0,:)
下标索引必须为正整数类型或逻辑类型。
矩阵转置
dataT = data';
获取向量、矩阵行数、列数
[m,n]=size(a)
size:获取数组的行数和列数
length:数组长度(即行数或列数中的较大值)
numel:元素总数。
size()
s=size(A)
,当只有一个输出参数时,返回一个行向量,该行向量的第一个元素时数组的行数,第二个元素是数组的列数。
[r,c]=size(A)
,当有两个输出参数时,size函数将数组的行数返回到第一个输出变量,将数组的列数返回到第二个输出变量。
如果在size函数的输入参数中再添加一项,并用1或2为该项赋值,则size将返回数组的行数或列数。 其中r=size(A,1)
该语句返回的时数组A的行数, c=size(A,2)
该语句返回的时数组A的列数。
n=numel(A)
该语句返回数组中元素的总数。
length(A)
n=length(A)
:如果A为非空数组,返回行数和列数两者之间数值较大的那一个值,即相当于执行了max(size(A))
;
如果A为空数组,则返回0;
排序 sort
Y=sort(X,DIM,MODE)
Y=sort(X)
sort()
的参数可以是向量,矩阵,数组等等。
当X
是向量时,sort(X)
对X的元素进行升序排序;
当X
是矩阵时,sort(X)
对X的每一列进行升序排序;
参数
DIM
表示对哪一个维数进行排序,例如当X是一个二维矩阵,当DIM=1
时表示对X的每一列进行排序,当DIM=2
时表示对X的每一行进行排序。
参数
MODE
表示按哪一种模式进行排序,
当MODE=‘ASCEND’
的时进行升序排序,当MODE=‘DESCEND’
时,进行降序排序。(默认升序)
如何找到一个数组中的最大值以及它所在的位置
>> s = [1 5 8 2 6]
s = 1 5 8 2 6
>> [max_v, index]=max(s)
max_v =
8
index =
3
Matlab中怎样写函数求数组中最大K个值的下标
A=[2,4,9,5,6,3,7]
[val,index]=sort(A)
val =[2 3 4 5 6 7 9]
index =[1 6 2 4 5 7 3]
再取出矩阵val的后面k个元素就可以了
判断矩阵是否存在某元素
ismember(item, Matrix)
:判断a矩阵有没有0这个元素
>> ismember(2,[1 2 3 5 8 9])
ans =
logical
1
>> ismember(4,[1 2 3 5 8 9])
ans =
logical
0
>> ismember(2,[1 2 3; 5 8 9])
ans =
logical
1
判断矩阵中某元素是否相等
all(A(:) == B(:))
isequal(A, B)
>> A = [1, NaN]
>> B = A
>> isequal(A, B)
0
>> NaN == NaN
0
但须注意的是:B = A,未必能保证 isequal(A, B)返回真,因为如果 A 中包含NaN,因为按照定义,NaN ~= NaN
对于浮点数矩阵,判断两个矩阵是否精确相等意义不大,真正有意义的比较是比较两个矩阵是否足够接近:
>> all(abs(A(:)-B(:))<col)
>> max(abs(A(:)-B(:))) < col
统计矩阵中某元素的数目
>> dag= [1 2 3;3 2 1; 2 4 4];
>> sum(dag(:)==1)
2
find()函数基本功能
find()函数的基本功能是返回向量或者矩阵中不为0的元素的位置索引
>> X = [1 0 4 -3 0 0 0 8 6];
>> ind = find(X)
ind =
1 3 4 8 9
其有多种用法,比如返回前k的不为0的元素:
>> ind = find(X,2)
ind =
1 3
也可以写成:
>> ind = find(X,2,'first')
> ind =
1 3
返回后k个不为0的元素:
>> ind = find(X,2,'last')
ind =
8 9
进阶
find()函数的功能是找到向量或者矩阵中不为0的元素,那如果需要找到其中满足一定条件的元素,比如,等于4的元素该怎么办呢?
>> X = [1 0 4 -3 0 0 0 8 6];
>> ind = find(X == 4)
ind =
3
高级
假如向量X的阶数很高,比如1000万维,如果我们用上面的方法,运行速度会很慢。仔细分析这个语句,我们其实并不希望找到X中等于9的全部元素,我们只想找到其中是否有等于9的元素,所以,我们只需作如下更改
isempty(find(X == 4,1))
结构体数组
for var=1 :var_size
var_row = MICs(var,:);
[mic_row_sort, micMaxIndex] = sort(var_row,'DESCEND');
varTop_k = micMaxIndex(1:TOPK);
topKNei(var).center = var;
topKNei(var).Nei = varTop_k;
end
如何生成一个集合的所有子集
A = 1:7;
b = arrayfun(@(k) nchoosek(A, k), 1:7, 'un', 0)
b{:}
怎么从一个向量中去掉一个元素
a(3)=[]
>> a=[1 2 3 4];
1 2 3 4
>> a(3)=[];
1 2 3
数 + 向量 ==> 向量
>> a=[1 2 3 4];
>> b=5;
>> [a,b]
[1 2 3 4 5]
>> [b,a]
[5 1 2 3 4]
fullBNT 函数learn_struct_mcmc.m
首先来说函数learn_struct_mcmc.m,此函数必须设置的输入参数比较少,大部分可以默认。仅两个必须的输入参数如下:
data和ns,含义与learn_struct_K2.m相同
% data(i,m) is the value of node i in case m.
% ns(i) is the number of discrete values node i can take on.
工具箱提供了函数learn_struct_K2.m的使用例子k2demo1.m,文件目录:\FullBNT-1.0.4\BNT\examples\static\StructLearn\k2demo1.m
causal_explorer toolkit
文献: Causal Explorer: A Causal Probabilistic Network Learning Toolkit for Biomedical Discovery
但是好像进不去,进不去的话就在github上面
Causal Explorer Download(github)
matlab中的addpath用法
addpath ABC;
% 或者
addpath(a);%a为路径
打开一个不在matlab工作路径上的文件,matlab会弹出提示。而如果文件在它的工作路径上,matlab就直接打开那个文件,不会弹出提示。用addpath把文件加入它的工作路径后,就不会弹出提示。
MATLAB中load函数的用法
求两个集合的 交集 和 并集
>> aa=[1 2 3]
>> bb=[2 3 4]
>> intersect(aa,bb)
>> union(aa,bb)
稀疏矩阵问题
>> S =
>> A = sparse([1 2 3],[2 3 2],[5 1 3],4,4) % 将全元素A转化为稀疏矩阵S
A =
(1,2) 5
(3,2) 3
(2,3) 1
>> A1=full(A) % % 将稀疏矩阵S转化为全元素矩阵A
A1 =
0 5 0 0
0 0 1 0
0 3 0 0
0 0 0 0
>>
DAG的构建,无环性检查
G = digraph(A)
creates a weighted directed graph using a square adjacency matrix, A. The location of each nonzero entry in A specifies an edge for the graph, and the weight of the edge is equal to the value of the entry. For example, ifA(2,1) = 10
, then G contains an edge from node 2 to node 1 with a weight of 10.
G = digraph(s,t)
specifies directed graph edges (s,t) in pairs to represent the source and target nodes. s and t can specify node indices or node names
% 构建有向图
% 按照邻接矩阵构建
G = digraph(A)
G = digraph(A,nodenames)
% 按照邻接矩阵构建
>> tf = isdag(G)
tf = logical
1
tf = isdag(G)
returns logical1
(true) if G is a directed acyclic graph; otherwise, it returns logical0
(false).
打印输出显示
用disp
>> str=['the value of pi=' num2str(pi)];
>> disp(str)
the value of pi=3.1416
此函数可联合num2str(将一个数转化为字符串)和int2str(讲一个整数转化为字符串)来产生新的信息,显示在命令行窗口中。例如,下面的语句将“the value of pi=3.1416”显示在命令行窗口中。第一句创建了一个字符型数组,第二句用于显示这个数组。
用fprintf函数格式化输出数据
>> fprintf('the value of pi is%6.2f\n',pi)
the value of pi is 3.14
format 命令 结果
%d 把值作为整数来处理
%e 用科学记数法来显示数据
%f 用于格式化浮点数,并显示这个数
%g 用科学记数格式,或浮点数格式,根据长度最短的显示
%n 换行符
随机数
>> rand() % rand是随机产生0—1中某一数
ans =
0.4346
>> randperm(9,1) % randperm是随机产生1—9中某 整数
ans =
5
>> randperm(9,2) % randperm是随机产生1—9中某两个 整数
ans =
6 5
randperm(n,m) % randperm是随机产生[1, n]中某m个 整数
repmat 重复数组副本
- 创建重复副本,放在M*N的数组中。
empty_particle.Position = [];
empty_particle.Velocity = [];
empty_particle.Cost = [];
empty_particle.Best.Position = [];
empty_particle.Best.Cost = [];
% Create Population Array
M = 10;
N = 50;
particle = repmat(empty_particle, M, N);
矩阵点乘
A=[1 2 3 4],B=[5 6 7 8],得到一个矩阵等于[1x5 2x6 3x7 4x8]
>> A=[1 2 3 4];B=[5 6 7 8];
>> C = A.*B
C =
5 12 21 32
时间
datestr() 将日期和时间转换为字符串格式
datetime
文件读写
dlmwrite
% 使用默认分隔符 “,” 将矩阵M写入文本文件filename中;
dlmwrite('filename', M)
% 使用分隔符D分割数据,“\t”表示tab分割,“,”为默认分割符;
dlmwrite('filename', M, 'D')
% 从矩阵M的第R行、第C列开始,作为要写矩阵块的左上角,将数据用D分割写入文件。
dlmwrite('filename', M, 'D', R, C)
% 将矩阵数据追加到文件的末尾。如果你不指定'-append',dlmwrite覆盖文件中的任何现有数据。
dlmwrite(filename, M, '-append')
% 接受一个属性值对列表。用户可以将'-append'标志放在属性-数值对之间,但不能放在属性和它的值的中间。
dlmwrite(filename, M, '-append', attribute-value list)
dlmread
Read ASCII-delimited file of numeric data into matrix
% reads an ASCII-delimited numeric data file into matrix M. The dlmread function detects the delimiter from the file and treats repeated white spaces as a single delimiter.
M = dlmread(filename)
% reads data from the file using the specified delimiter and treats repeated delimiter characters as separate delimiters.
M = dlmread(filename,delimiter)
% starts reading at row offset R1 and column offset C1. For example, the offsets R1=0, C1=0 specify the first value in the file.
M = dlmread(filename,delimiter,R1,C1)
% reads only the range bounded by row offsets R1 and R2 and column offsets C1 and C2. Another way to define the range is to use spreadsheet notation, such as 'A1..B7' instead of [0 0 6 1].
M = dlmread(filename,delimiter,[R1 C1 R2 C2])
M = dlmread('count.dat')
M = 24×3
11 11 9
7 13 11
14 17 20
11 13 9
43 51 69
38 46 76
61 132 186
75 135 180
38 88 115
28 36 55
⋮
.m文件批量转换为 .p 文件
%% 批量 .m 文件转换为 .p 文件
% 'D:\code\program\projectName' 中所有.m文件转换为 .p 文件
testpath = 'D:\code\program\';
pName = 'projectName';
trans_m_to_p(path, pName)
function flag = isdots(dirname)
flag1 = strcmp(dirname, '.');
flag2 = strcmp(dirname, '..');
flag = 0;
if flag1 || flag2
flag = 1;
end
end
function trans_m_to_p(dirPath, dfName)
if isdots(dfName)
return;
end
path = [dirPath, dfName];
if ~exist(path, 'dir') % 不是文件夹
pcode(dfName,'-inplace')
else % 是文件夹
path = [path, '\'];
listdirstruct = dir(path);
len_lds = length(listdirstruct);
for dirIndex = 1:len_lds
dirname = listdirstruct(dirIndex).name;
trans_m_to_p(path, dirname);
end
end
end
matlab程序打包
- 使用Application Complier
打包成 exe
https://blog.csdn.net/subtitle_/article/details/122589180
- App打包
当然这个app必须在matlab环境下才能使用,需要打开matlab,点击安装App,选择刚才生成的mlappinstall文件的路径
画图
% sets the line style, marker symbol, and color.
% (实线、虚线) (点的形状) (颜色)
% Line style, marker, and color, specified as a character vector or string containing symbols.
% Example: '--or' is a red dashed line with circle markers
plot(X,Y,'--or')
数据点的形状 | 描述 | 线的风格 | 描述 | 颜色 | 描述 |
---|---|---|---|---|---|
o | Circle | - | Solid line (default) | y | yellow |
+ | Plus sign | - - | Dashed line | m | magenta |
* | Asterisk | : | Dotted line | c | cyan |
. | Point | -. | Dash-dot line | r | red |
x | Cross | g | green | ||
s | Square | b | blue | ||
d | Diamond | w | white | ||
^ | Upward-pointing triangle | k | black | ||
v | Downward-pointing triangle | ||||
> | Right-pointing triangle | ||||
< | Left-pointing triangle | ||||
p | Pentagram | ||||
h | Hexagram |
一条线
% 100个点的x座标
x=linspace(0, 2*pi, 100);
% 对应的y座标
y=sin(x);
% 画图
plot(x,y);
多条线
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
% 画布
figure
plot(x,y1,x,y2)
矩阵画线
>> Y = magic(4)
Y = 4×4
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
figure
plot(Y)
线宽调整
这里'--gs'
表示用方框画点,然后用绿色虚线连结;'LineWidth',2
表示绿色虚线宽度为2
;'MarkerSize',10
表示方框大小为10;'MarkerEdgeColor','b'
表示方框边缘颜色为蓝色;'MarkerFaceColor',[0.5,0.5,0.5]
表示方框填充色为[0.5,0.5,0.5]
(这是RGB颜色值)。例如:
>> x = -pi:pi/10:pi;
>> y = tan(sin(x)) - sin(tan(x));
>> plot(x,y,'--gs','LineWidth',2,'MarkerSize',10,'MarkerEdgeColor','b','MarkerFaceColor',[0.5,0.5,0.5])
>> xlabel('x')
>> ylabel('y')
参考
数学建模之MATLAB画图汇总
mesh 三维网格图
plot3、mesh