-
python 深度模仿 matlab 矩阵语法
2015-08-28 20:57:02MyMat (298行开始)类模仿matlab矩阵索引与赋值。从1开始计数,倒数从0开始。可以用单指标索引:1为第一个元素,2 为第一列第二行元素……以后还会加以改进。网友们也可以提出一些建议。( 代码以pypi为准 ) ...直接上代码。MyMat (298行开始)类模仿matlab矩阵索引与赋值。从1开始计数,倒数从0开始。可以用单指标索引:1为第一个元素,2 为第一列第二行元素……以后还会加以改进。网友们也可以提出一些建议。(代码以pypi为准)
If you like matlab as well as python, then this is your choice. Class MyMat imitates the reference and assignment of matlab matrices. The index is form 1, instead of 0, and the last index is 0, instead of -1. I will add more functions or classes in the future to improve the modules. You can give me any advice under the article.
You can download the codes from pypi. https://pypi.python.org/pypi/mymat
截止10月1日(接近一个月),至少已有九千人下载代码。
</pre><p></p><p><pre name="code" class="python">import numpy as np import numpy.linalg as LA '''notation (abbreviation): num: complex number ind: index (int, slice or list, or tuple of index sometimes) sglind: single index (int, slice or list) vec: vector colvec: column vector slc: slice ran: range lst: list mat: matrix r(m): row c(n): column ''' # python for my matrix type # special matrices def O(m, n=None): # 0 matrix if n==None: n = m return MyMat(np.zeros((m, n))) def One(m, n=None): # 1 matrix if n==None: n = m return MyMat(np.ones((m, n))) def I(m, n=None): # identity matrix if n==None: n = m return MyMat(np.eye(m, n)) def E(i,j,m,n=None): if n==None: n = m A = O(m,n) A[i,j] = 1 return A def R(m, n=None, randfun='rand'): # random matrix if n==None: n = m return MyMat(getattr(np.random, randfun)(m, n)) def H(m, n=None): # Hilbert matrix if n==None: n = m return MyMat([[1 / (k + l - 1) for l in range(1, n+1)] for k in range(1, m+1)]) def TestMat(m, n=None): if n==None: n = m return MyMat([[l + (k-1)*n for l in range(1, n+1)] for k in range(1, m+1)]) # maps def mat_map(f,*As): # matrices (np.matrix) in As have the same size rn, cn = As[0].shape # size (shape) of matrix return np.mat([[f(*(A[k, l] for A in As)) for l in range(cn)] for k in range(rn)]) def mymat_map(f,*As): # matrices (MyMat) in As have the same size rn, cn = As[0].shape # size (shape) of matrix return MyMat([[f(*(A[k, l] for A in As)) for l in range(1, cn+1)] for k in range(1, rn+1)]) # relations # will be used in test def equal(A, *Ms): if myMat(A).isempty(): for M in Ms: if not MyMat(M).isempty(): return False return True for M in Ms: M = np.mat(M) if A.shape != M.shape or (A != M).any(): return False return True def equal_tol(A, *Ms, tol=0.001): for k, M in enumerate(Ms): M = np.mat(M) for N in Ms[k+1:]: N = np.mat(N) if A.shape != M.shape or LA.norm(A - M)>=tol: return False return True ''' # Index class # it may be used in the future def indadd(ind, x): if isinstance(ind, int): return ind + x elif isinstance(ind, slice): return slice(ind.start + x, ind.stop + x, ind.step) else: return [a + x for a in ind] def indinv(ind): if isinstance(ind, int): return ind elif isinstance(ind, slice): return slice(ind.stop, ind.start, -ind.step) else: ind.reverse() return ind def indneg(ind): if isinstance(ind, int): return -ind elif isinstance(ind, slice): return slice(-ind.stop, -ind.start, -ind.step) else: return [-a for a in ind] class Index: # value: int, slice, list def __init__(self, value=0): self.value=value def __add__(self, other): if isinstance(other, int): return Index(indadd(self.value, other)) def __neg__(self): return Index(indneg(self.value)) def __invert__(self): return Index(indinv(self.value)) def __str__(self): return ','.join(map(str, ind2iter(self.value))) ''' # MyMat Class def isreal(x): return isinstance(x, (int, float)) def isnum(x): return np.isscalar(x) def isscalar(x): return isnum(x) or isinstance(x, MyMat) and x.isscalar() def issgl(x): # single index used in python return isinstance(x, (int, slice, list)) def isemp(x): # empty index return isinstance(x, list) and x==[] or isinstance(x, tuple) and (x[0]==[] or x[1]==[]) def iscrd(x): # coordinate type index # isinstance(x, tuple) and len(x) == 2 return isinstance(x, tuple) and isinstance(x[0], list) and isinstance(x[1], list) COLON = slice(None) # transform of the indices import itertools def times(ind): ''' >>> times(([1,2],[3,4,6])) ([1, 1, 1, 2, 2, 2], [3, 4, 6, 3, 4, 6]) ''' if iscrd(ind): lst = itertools.product(ind[0],ind[1]) b=([], []) for a in lst: b[0].append(a[0]) b[1].append(a[1]) return b else: return ind def ind2iter(ind, N): # slice to range, int and list to list if isinstance(ind, list): return ind elif isinstance(ind, slice): # slc is a slice a = ind.start if ind.start else 0 b = ind.stop if ind.stop else N # b <= N return range(a, b, c) if ind.step else range(a,b) else: return [ind] def ind2list(ind, N): # slice to range, int and list to list if isinstance(ind, list): return ind elif isinstance(ind, slice): # slc is a slice a = ind.start if ind.start else 0 b = ind.stop if ind.stop else N # b <= N return list(range(a, b, c)) if ind.step else list(range(a,b)) else: return [ind] def ind2ind(ind): '''index of matlab type to index of python type This is the main gimmick to define MyMat also see slice2slice ''' if isinstance(ind, tuple): return tuple(ind2ind(a) for a in ind) if isinstance(ind, list): return [a - 1 for a in ind] elif isinstance(ind, slice): return slice2slice(ind) # see its definition else: return ind - 1 def slice2slice(slc): '''slice of matlab type to slice of python type for example: M[1:3] := M[0:3] >>> slice2slice(slice(1, 6, 2)) slice(0, 6, 2) >>> slice2slice(slice(-3, 0)) slice(-4, None, None) ''' return slice(slc.start-1 if slc.start else None, None if slc.stop == 0 else slc.stop, slc.step) def int2pair(ind, r, c=1): ''' >>> int2pair(ind2ind([3,4,7,10]),5,5) ([2, 3, 1, 4], [0, 0, 1, 1]) ''' if isinstance(ind, int): return np.mod(ind, r), np.floor_divide(ind, r) else: ind=ind2iter(ind, r*c) return [np.mod(a, r) for a in ind], [np.floor_divide(a, r) for a in ind] def pair2int(ind, r, c=None): '''inverse of int2pair >>> pair2int(int2pair([4,7,12,22],5,5),5,5) [4, 7, 12, 22] ''' if isinstance(ind[0], int) and isinstance(ind[1], int): return ind[0] + r * ind[1] else: if c==None: c=max(ind[1]) return [a + r * b for a, b in zip(ind2iter(ind[0], r), ind2iter(ind[1], c))] """ # int2pair(ind2ind) == ind2ind(int2pair2) def int2pair2(ind, r, c=1): '''single index (int) => pair index (tuple) example: >>> int2pair(7, 3) (1, 3) if isinstance(ind, int): return (r, np.floor_divide(ind, r)) if np.mod(ind, r)==0 else (np.mod(ind, r), np.floor_divide(ind, r)+1) else: # extend to lists or slices ind=ind2iter(ind, r * c) p=([],[]) for a in ind: if np.mod(a, r)==0: p[0].append(r); p[1].append(np.floor_divide(a, r)) else: p[0].append(np.mod(a, r)); p[1].append(np.floor_divide(a, r)+1) return p """ def maxind(ind): # if issgl(ind): if isinstance(ind, int): return ind elif isinstance(ind, list): return max(ind) elif isinstance(ind, slice): return ind.stop if ind.stop else 0 else: return maxind(ind[0]), maxind(ind[1]) # definition of MyMat Class class MyMat(np.matrix): # python for imitating matrices (2D) in matlab # matrix on complex numbers def __new__(cls, data, *args, **kw): if isinstance(data, list): data=np.array(data) elif isinstance(data, str): data = np.array(np.matrix(data)) elif hasattr(data, 'tolist'): data = np.array(data.tolist()) return super(MyMat, cls).__new__(cls, data, *args, **kw) def __mul__(self, other): if isinstance(other, MyMat): if other.isscalar(): return super(MyMat, self).__mul__(other.toscalar()) else: return super(MyMat, self).__mul__(other) else: if self.isscalar(): return MyMat([self[1,1] * other]) else: return super(MyMat, self).__mul__(other) def __rmul__(self, other): return self * other def __imul__(self, other): self[:,:] = self * other return self def __pow__(self, other): # A**B := A.*B return MyMat(np.multiply(self, other)) def __rpow__(self, other): # B**A := B.*A return MyMat(np.multiply(other, self)) def __ipow__(self, other): self[:,:] = self ** other return self def __floordiv__(self, other): # A//B := A./B return MyMat(np.divide(self, other)) def __rfloordiv__(self, other): # B//A := B./A return MyMat(np.divide(other, self)) def __ifloordiv__(self, other): self[:,:] = self // other return self def __truediv__(self, other): # A/B := A/B (A*inv(B)) if isinstance(other, MyMat) and other.isscalar(): return MyMat(np.divide(self, other.toscalar())) elif isnum(other): return self * (1 / other) # = 1/other * self return self * other.I def __rtruediv__(self, other): # r/A := r/A (r * inv(A)) return other * self.I def __itruediv__(self, other): self[:,:] = self / other return self def __xor__(self, num): # A^n := A^n, n is int if isinstance(num, MyMat) and num.isscalar(): return super(MyMat, self).__pow__(num.toscalar()) return super(MyMat, self).__pow__(num) def __rxor__(self, num): pass def __ixor__(self, num): self[:,:] = self ^ other return self def __lshift__(self, other): # A<<B := A.^B return MyMat(np.power(self, other)) def __rlshift__(self, other): # r<<A := r.^A return MyMat(np.power(other, self)) def __ilshift__(self, other): self[:,:] = self << other return self @property def I(self): return self.getI() def __getitem__(self, ind): r, c = self.shape if iscrd(ind): return self.get((ind[0], COLON)).get((COLON, ind[1])) else: return self.get(ind) def __setitem__(self, ind, val): r, c = self.shape if issgl(ind): self.set(ind, val) else: if iscrd(ind): if isinstance(val, MyMat): if val.isscalar(): self.set(times(ind), val.toscalar()) else: self.set(times(ind), val.tovec(dim=2).tolist()) elif isnum(val): self.set(times(ind), val) else: # isinstance(val, list) self.set(times(ind), val) else: self.set(ind, val) def get(self, ind): r, c = self.shape if issgl(ind): return super(MyMat, self).__getitem__(int2pair(ind2ind(ind), r, c)) return super(MyMat, self).__getitem__(ind2ind(ind)) def set(self, ind, val): r, c = self.shape if issgl(ind): # single index mx=maxind(ind) if mx > r*c: mx1, mx2=int2pair(mx-1, r, c) self.just(max(r, mx1+1), max(c, mx2+1)) if isnum(val): super(MyMat, self).__setitem__(int2pair(ind2ind(ind), r, c), val) elif isinstance(val, list): super(MyMat, self).__setitem__(int2pair(ind2ind(ind), r, c), val) elif isinstance(val, MyMat): if val.isscalar(): super(MyMat, self).__setitem__(int2pair(ind2ind(ind), r, c), val[1, 1]) elif val.isvec(): super(MyMat, self).__setitem__(int2pair(ind2ind(ind), r, c), val.tolist()) elif val.iscolvec(): super(MyMat, self).__setitem__(int2pair(ind2ind(ind), r, c), val.T.tolist()) elif isinstance(val, np.matrix): self.set(ind, MyMat(val)) else: # double index mx1, mx2 = maxind(ind) if mx1 > r or mx2 > c: self.just(max(r, mx1), max(c, mx2)) if isinstance(ind[0], slice) and isinstance(ind[0], slice): super(MyMat, self).__setitem__(ind, val) else: super(MyMat, self).__setitem__(ind2ind(ind), val) ''' def set_(self, ind, val): # extension of setitem r, c = self.shape if issgl(ind): mx=maxind(ind) if mx > r*c: mx1, mx2=int2pair(mx-1, r, c) self.just(max(r, mx1+1), max(c, mx2+1)) else: mx1, mx2 = maxind(ind) if mx1 > r or mx2 > c: self.just(max(r, mx1), max(c, mx2)) self.set(ind, val) return self ''' def update(self, other): self.resize(other.shape, refcheck=False) super(MyMat, self).__setitem__((COLON, COLON), other) def __call__(self, *ind): if len(ind)==1: return self[ind[0]] return self[ind] def __str__(self): return '['+self.join(ch2=';\n ')+']' def join(self, ch1=', ', ch2='; '): r, c = self.shape return ch2.join(ch1.join(str(super(MyMat, self).__getitem__((k, l))) for l in range(c)) for k in range(r)) def cat(self, *others, dim=1): if self.isempty(): return np.concatenate(others, axis=dim-1) elif not others: return self else: return np.concatenate((self,)+others, axis=dim-1) def __or__(self, other): return np.concatenate((self, other), 1) def __ior__(self, other): self.update(self | other) return self def __and__(self, other): return np.concatenate((self, other)) def __iand__(self, other): self.update(self & other) return self def wequal(self, *others): # weakly equal if self.isempty(): for other in others: if not MyMat(other).isempty(): return False return True for other in others: M = MyMat(other) if self.shape != M.shape or (self != M).any(): return False return True def equal(self, *others): # others are MyMat if self.isempty(): for other in others: if not other.isempty(): return False return True for other in others: if self.shape != other.shape or (self != M).any(): return False return True def toscalar(self): return super(MyMat, self).__getitem__((0,0)) def tolist(self): if self.isvec(): return super(MyMat, self).tolist()[0] else: return super(MyMat, self).tolist() def toarray(self): if self.isvec(): return self.A1 else: return self.A def tomatrix(self): return np.matrix(self.tolist()) def tomat(self): # == tomatrix return np.mat(self.tolist()) def tovec(self, dim=1): if dim==1: return MyMat([[self[k, l]] for l in range(1, self.shape[1]+1) for k in range(1, self.shape[0]+1)]) elif dim==2: lst=[] for k in range(1, self.shape[0]+1): lst.extend(self[k,:].tolist()) return MyMat(lst) def just(self, m, n=None): if n == None: n = m r, c = self.shape if m>0 and n>0: if m<=r: temp = super(MyMat, self).__getitem__((slice(m), slice(r))) else: temp = self | O(m - r, c) if n<=c: temp = super(MyMat, temp).__getitem__((slice(c), slice(n))) else: temp = temp & O(m, n - c) elif m==0 or n==0: temp = Empty else: temp = O(abs(m), abs(n)) self.update(temp) # return self def delete(self, ind1=[], ind2=[]): r, c = self.shape if not isemp(ind1): ind1=ind2list(ind2ind(ind1), r) if ind1 == list(range(r)): return Empty self=np.concatenate(tuple(super(MyMat, self).__getitem__((slice(a+1,b), COLON)) for a, b in zip([-1]+ind1, ind1+[r]) if b-a!=1)) if not isemp(ind2): ind2=ind2list(ind2ind(ind2), c) if ind2 == list(range(c)): return Empty return np.concatenate(tuple(super(MyMat, self).__getitem__((COLON, slice(a+1,b))) for a, b in zip([-1]+ind2, ind2+[c]) if b-a!=1), 1) else: return self '''def delete(self, ind1, ind2): ...... if not isemtpy(ind1): self=super(PyMat, self).__getitem__((slice(ind1[0]), COLON)).cat( *(tuple(super(PyMat, self).__getitem__((slice(a+1,b), COLON)) for a, b in zip(ind1[:-1], ind1[1:]) if b-a!=1) +(super(PyMat, self).__getitem__((slice(ind1[-1]+1,None), COLON)),))) if self.isempty(): return Empty if not isemtpy(ind2): return super(PyMat, self).__getitem__((COLON, slice(ind2[0]))).cat( *(tuple(super(PyMat, self).__getitem__((COLON, slice(a+1,b))) for a, b in zip(ind2[:-1], ind2[1:]) if b-a!=1) +(super(PyMat, self).__getitem__((COLON, slice(ind2[-1]+1,None))),)), dim=2) else: return self''' def norm(self, p=2): if self.isvec(): return LA.norm(self.toarray(), p) elif self.iscolvec(): return LA.norm(self.T.toarray(), p) else: return LA.norm(self, p) def repmat(self, m=1): return np.tile(self, m-1) def apply(self, fun): return mymat_map(fun, self) def isempty(self): return self.shape[1]==0 or self.shape[0]==0 def isscalar(self): return self.shape == (1,1) def isvec(self): return self.shape[0] == 1 def iscolvec(self): return self.shape[1] == 1 @property def size(self): return self.shape def poly(self, p): # self is a square matrix r, c = self.shape # r == c if len(p)==1: return p[0]*I(r) return p[0]*I(r)+self.poly(p[1:])*self def expm(self, N=10): p=[1/np.prod(range(1, n+1)) for n in range(N)] return self.poly(p) # matrix instance MMat = myMat = MyMat # alias Empty = MyMat([]) # empty set im = MyMat([[0, 1], [-1, 0]]) def c(a=0, b=0): # linear represenation of complex number return MyMat([[a, b], [-b, a]]) def q(a=0, b=0, c=0, d=0): # linear represenation of quaternions return MyMat([[a, b, c, d], [-b, a, -d, c], [-c, d, a, -b], [-d, -c, b, a]])
-
matlab矩阵操作
2012-05-21 09:35:52matlab矩阵操作语法,对初学者有帮助!比较实用 -
matlab的基本语法规则_matlab的基本语法规则_MATLAB基本语法
2021-03-13 11:26:11点乘运算,常与其他运算符点乘运算,常与其他运算符联合使用(如.\)矩阵生成 矩阵生成 向量生成或子阵提取本节将会介绍一些MATLAB的基本语法的使用。在 MATLAB 环境下进行的操作就像是使用一个超级复杂的计算器,不要被...点乘运算
,
常与其他运算符
点乘运算,常与其他运算符联合使用(如.\)
矩阵生成 矩阵生成 向量生成或子阵提取本节将会介绍一些MATLAB的基本语法的使用。在 MATLAB 环境下进行的操作就像是使用一个超级复杂的计算器,不要被这吓到了。在您开始使用 MATLAB 时可以在“>>”命令提示符下输入命令。
执行MATLAB命令MATLAB 是一种解释型的环境。也就是说,只要你给MATLAB一个命令,它就会马上开始执行。
MATLAB实践
在">>" 命令提示符下键入一个有效的表达,例如:5 + 5
然后按 ENTER 键
当点击“执行”按钮,或者按“Ctrl+ E”,MATLAB执行它并返回结果:ans = 10
让我们使用几个例子:3 ^ 2 % 3 raised to the power of 2
当你点击“执行”按钮,或者按“Ctrl+ E”,MATLAB执行它并返回结果:ans = 9
另外一个例子:sin(pi /2) % sine of angle 90o
当你点击“执行”按钮,或者按“Ctrl+ E”,MATLAB执行它并返回结果:ans = 1
另外一个例子,7/0 % Divide by zero
当点击“执行”按钮,或者按“Ctrl+ E”,MATLAB执行它并返回结果:ans = Inf
warning: division by zero
另外一个例子,732 * 20.3
当点击“执行”按钮,或者按“Ctrl+ E”,MATLAB执行它并返回结果:ans = 1.4860e+04
MATLAB 提供了一些特殊的一些数学符号的表达,像圆周率 π, Inf for ∞, i (and j) for √-1 etc. Nan 代表“不是一个数字”。
MATLAB常用的运算符和特殊字符
MATLAB常用的运算符和特殊字符如下表所示:运算符目的
+加;加法运算符
-减;减法运算符
*标量和矩阵乘法运算符
.*数组乘法运算符
^标量和矩阵求幂运算符
.^数组求幂运算符
\矩阵左除
/矩阵右除
.\阵列左除
./阵列右除
:向量生成;子阵提取
( )下标运算;参数定义
[ ]矩阵生成
.点乘运算,常与其他运算符联合使用
…续行标志;行连续运算符
,分行符(该行结果不显示)
;语句结束;分行符(该行结果显示)
%注释标志
_引用符号和转置运算符
._非共轭转置运算符
=赋值运算符
MATLAB常用的运算符使用示例
MATLAB分号(;)使用
MATLAB中分号(;)表示语句结束;但是,如果想抑制和隐藏 MATLAB 输出表达,表达后添加一个分号。
例如,x = 3;
y = x + 5
当点击“执行”按钮,或者按“Ctrl+ E”,MATLAB执行它立即返回的结果是:y = 8
MATLAB添加注释
MATLAB的百分比符号(%)是用于表示一个注释行。例如:x = 9 % assign the value 9 to x
也可以写注释,使用一块块注释操作符%{%}。
MATLAB编辑器包括工具和上下文菜单项,来帮助添加,删除或更改注释的格式。
MATLAB特殊变量和常量
MATLAB支持以下特殊变量和常量:NameMeaning
ans默认的变量名,以应答最近依次操作运算结果
eps浮点数的相对误差
i,j虚数单位,定义为 i2= j2= -1
Inf代表无穷大
NaN代表不定值(不是数字)
pi圆周率
MATLAB命名变量
变量名称是由一个字母后由任意数量的字母,数字或下划线。
注意MATLAB中是区分大小写的。
变量名可以是任意长度,但是,MATLAB使用只有前N个字符,其中N是由函数namelengthmax。
保存你的工作进度
MATLAB使用save命令保存工作区中的所有变量,然后作为一个扩展名为.mat的文件,在当前目录中。
如以下例子:save myfile
该文件可以随时重新加载,然后使用load命令。load myfile
-
MATLAB矩阵处理
2013-06-07 22:56:36标题:MATLAB矩阵 内容:MATLAB是MATrix LABoratory的简称,数据的处理是以矩阵为基本单位的。 作者:MilkCu(http://blog.csdn.net/milkcu) 矩阵的建立 命令窗口直接输入 优点: 灵活构建任意结构、任意数据的矩阵...欢迎访问我的新博客:http://www.milkcu.com/blog/
原文地址:http://www.milkcu.com/blog/archives/1370588160.html
标题:MATLAB矩阵
内容:MATLAB是MATrix LABoratory的简称,数据的处理是以矩阵为基本单位的。
作者:MilkCu(http://blog.csdn.net/milkcu)
矩阵的建立
命令窗口直接输入
优点:
灵活构建任意结构、任意数据的矩阵;语法规则:
- 矩阵元素应当放在方括号内;
- 行内元素用逗号或空格隔开;
- 行之间用分号或回车分隔;
- 元素可以是数值或表达式;
使用“from : step : to”方式
只能生成线性的、等间隔的向量。
当参数step省略时,系统默认step = 1。
使用linspace函数
在指定区间内生成线性等分向量。中间的值,将根据a、b及向量个数n等分产生。
调用格式为linspace(a, b, n)。
其中a表示向量的第一个值,b表示向量的最后一个值,n表示向量中元素的个数。
当参数n省略时,系统默认n = 100。使用logspace函数
调用格式为logspace(a, b, n)。
其中a表示向量的第一个值以10为底的幂,b表示向量的最后一个值以10为底的幂,n表示向量中元素的个数。
当参数n省略时,系统默认n = 50。从外部数据文件导入
通过菜单File -> Import Data进行。
特殊矩阵
产生特殊类型矩阵的函数 函数 作用 zeros(m, n) 产生m * n的全0矩阵 ones(m, n) 产生m * n全1矩阵 eye(m, n) 产生m * n单位矩阵 rand(m, n) 产生m * n,以0~1随机矩阵 randn(m, n) 产生m * n,均值为0,方差为1的高斯分布的矩阵 randperm(n) 产生整数1~n的随机排列 magic(n) 产生n阶魔方矩阵 魔方矩阵:每行、列、对角线上的元素和相等。
矩阵下标
全下标方式
第i行j列的元素表示为a(i, j)。
在对元素赋值时,如果i > m或j > n,系统不会报错,并对其余扩充部分以0填充。
单下标方式
矩阵的元素在系统中,仍然以线性方式存储。
用a(x)来表示矩阵的元素。
注意:矩阵元素的读取顺序为“列优先”。
单下标方式a(x)和全下标方式a(i, j),其下标换算公式为x = (i - 1) * m + j。
子矩阵
- a(:, n)表示矩阵a的所有行与第n列,即提取矩阵a第n列元素。
- a([m n], [i j])表示矩阵第m行与第n行的第i列与第j列。
- a(m1 : m2, n1 : n2)表示矩阵的第m1行至第m2行的第n1列至第n2列。
- a(m : end, n)表示矩阵a的第m行至最末行的第n列。
- a(:, :)表示一个长列矢量,该矢量的元素按矩阵的列进行排列。
矩阵的赋值
矩阵赋值方式 赋值方式 使用方法 说明 全下标 a(i, j) = b 给矩阵a的部分元素赋值 单下标 a(s) = b b为向量,元素个数对应相等 全元素 a( : ) = b 元素总数相等,但行列数可以不同 矩阵元素的删除
利用方括号([ ])删除矩阵的某行列,或者它的子矩阵。
矩阵的合并
可以使用方括号([ ]),将小的矩阵合并成一个大矩阵。
但要注意行列数是否匹配。
矩阵函数
- transpose(A);矩阵A的转置。可以用单引号(')代替。
- mean(A);函数返回行向量,各元素对应A中相应列的算术平均值。
- mean(A, dim):当dim = 1时,功能同上;当dim = 2时,返回值为列向量,各元素对应A中相应行的算术平方根。
(全文完)
-
杭电Matlab与仿真-MATLAB基本语法(五)-矩阵分析
2020-07-23 11:11:13矩阵分析实验目的实验内容与要求实验程序与结果 实验目的 掌握基本的2*2矩阵变换; 掌握矩阵分析的方法。 实验内容与要求 认识基本的线性变换矩阵及随机线性变换矩阵; 掌握绘制出自己手型的方法; 掌握各种基本...实验目的
- 掌握基本的2*2矩阵变换;
- 掌握矩阵分析的方法。
实验内容与要求
- 认识基本的线性变换矩阵及随机线性变换矩阵;
- 掌握绘制出自己手型的方法;
- 掌握各种基本的矩阵分析方法;
- 能够运用矩阵分析解决问题。
实验程序与结果
- 给自己的手做变换。采集自己的手型图,绘制出该图的镜像图。
所用函数
function dot2dot(X) X(:,end+1) = X(:,1); plot(X(1,:),X(2,:),'.-','markersize',18,'linewidth',2) axis(10*[-1 1 -1 1]) axis square
各绘制点的采集
figure('position',get(0,'screensize')) axes('position',[0 0 1 1]),axis(10*[-1 1 -1 1]) [x,y]=ginput; H=[x,y]; M=[-x,y]; save myhand H save myhand2 M
图像绘制:
load myhand; load myhand2; subplot(1,2,1),dot2dot(H') subplot(1,2,2),dot2dot(M')
- 课本P123.8
a=[2,4,9;4,2,4;9,4,18]; [j,k]=eig(a)
- P123.14
k=rand(4,4)*10 [o,p]=lu(k) [m,n]=qr(k)
- 画一个以原点为圆心,半径为10的圆,并在圆内区域随机产生20个数据点。
a=2*pi*rand(1,20); r=rand(1,20)*10; x=sin(a).*r; y=cos(a).*r; c=0:2*pi/1000:2*pi; plot(10*sin(c),10*cos(c),x,y,'o')
-
matlab的基本语法规则_MATLAB基本语法
2020-12-22 04:47:44点乘运算,常与其他运算符点乘运算,常与其他运算符联合使用(如.\)矩阵生成 矩阵生成 向量生成或子阵提取本节将会介绍一些MATLAB的基本语法的使用。在 MATLAB 环境下进行的操作就像是使用一个超级复杂的计算器,不要被... -
matlab基本语法
2019-06-03 23:07:00矩阵生成 矩阵生成 向量生成或子阵提取本节将会介绍一些MATLAB的基本语法的使用。 持续更新。。。 在 MATLAB 环境下进行的操作就像是使用一个超级复杂的计算器,不要被这吓到了。在您开始使用 MATLAB 时可以... -
Matlab基础语法
2020-02-02 22:17:02Matlab基础语法内容概述运算符号矩阵输入输出选择判断取模函数function画图总结 内容概述 2020.02.02一更 你好呀!初学Matlab,做一个记录。本文适合有C基础的Matlab小白(我自己)。 力求简短,文章多用代码举例。 ... -
matlab元胞数组转字符串矩阵_Julia/Python/Matlab基本语法比较
2020-11-21 10:57:51完整的免费的Julia视频教程:Julia 教程 从入门到进阶 - 网易云课堂study.163.com 相信很多朋友刚开始做算法时应该都是用matlab做理论模型的验证,后来Python大火,很多小伙伴又争相学起来python,可过了没多久,... -
matlab的基本语法规则_matlab基本语法
2020-12-22 04:47:47MATLAB简介MATLAB(MATrixLABoratory,即矩阵实验室)是MathWork公司推出的一套高效率的数值计算和可视化软件。MATLAB是当今科学界最具影响力、也是最具活力的软件,它起源于矩阵运算,并已经发展成一种高度集成的... -
MATLAB之基本语法之矩阵生成及矩阵提取及矩阵操作
2017-07-29 09:17:00MATLAB基本运算单元为矩阵,所以我们需要了解对矩阵的一些简单的语法操作。 1、如何生成一个矩阵(来自百度) (1)元素输入法 (2)设定步长生成 形式为: A=a:inc:b 可以看出a为初值,inc为步长... -
matlab语法
2020-07-23 16:14:44matlab语法矩阵语法求和二级目录三级目录 矩阵语法 求和 输入一个3x3矩阵r >> sum(r,1) 求列的和 结果: ans = 3 6 9 >> sum(r,2) 求行的和 结果: ans = 6 6 6 >> a=sum(sum(r)) 求... -
MATLAB01:基本的数学运算与矩阵运算
2019-11-12 17:22:52MATLAB01:基本的数学运算与矩阵运算MATLAB基本语法变量变量名保留变量不适合做变量名变量不应当覆盖内置函数MATLAB的调用优先级变量类型数字型变量的显示格式MATLAB命令行使用MATLAB进行数字运算使用MATLAB计算数学... -
Matlab基本语法
2021-01-24 21:28:57Matlab基本命令 数据类型 变量 常量 数值 运算符 点运算与除法 关系与逻辑运算符 函数运算 向量 向量生成 向量元素的引用 向量运算 四则运算 点积和叉积 多项式 创建多项式 多项式四则与导数运算 特殊... -
matlab的基本语法规则_MATLAB基础语法
2021-03-13 11:25:449 10 11 12]%产生一个矩阵disp(x)%显示这个矩阵x=zeros(1,6)%产生一个16的0矩阵x=zeros(6)%产生一个66的0矩阵x=ones(6)%产生一个66的全1矩阵x=ones(1,6)%产生一个16的全1矩阵常用函数###dir%列出现在目录中的档案exp... -
matlab基础语法记录
2021-01-07 00:24:35以及将python程序转换为matlab程序,发现matlab用于计算最牛逼,python稍微差点,java那是真的恶心,特别是double类型的计算有精度丢失问题,还有引用传递,如果用java进行数学计算,特别是矩阵计算,特别要注意这两... -
MATLAB基本语法
2019-11-05 09:35:33MATLAB常用的运算符和特殊字符 MATLAB常用的运算符和特殊字符如下表所示: 运算符 目的 + 加;加法运算符 - 减;减法运算符 * 标量和矩阵乘法运算符 .* 数组乘法运算符 ^ 标量和矩阵... -
Matlab学习语法一
2021-04-05 10:54:54Matlab学习语法一 1:zeros函数 例子: X = zeros(4) X = 4×4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2:drag函数 生成对角矩阵,如下例: A=[zeros(4,1),diag([0.025,0.015,0.055,0.026])]; 生成下图矩阵: 3... -
matlab 提取数列里非零_MATLAB之基本语法之矩阵生成及矩阵提取及矩阵操作
2021-01-27 07:46:15MATLAB基本运算单元为矩阵,所以我们需要了解对矩阵的一些简单的语法操作。1、如何生成一个矩阵(来自百度)(1)元素输入法(2)设定步长生成形式为: A=a:inc:b可以看出a为初值,inc为步长,b为终值(界限) 相当于生成了...