matlab学习

本文详细介绍了MATLAB的基础矩阵操作,包括创建、索引、矩阵运算及矩阵函数的使用,如指数与对数、矩阵乘法、差分、单位矩阵、随机数生成等。此外,还涵盖了读取和显示数据的方法、循环控制、函数定义以及图形绘制。文章通过实例展示了如何利用牛顿法求解方程,以及如何进行数据处理和画图,包括误差棒图、双轴图和等值线图的绘制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

% pwd, cd, cd.. 
% 一.基础矩阵
% log(pi)=ln(pi) lg(pi)=log10(pi)
% 创建矩阵 空格/逗号,有负数用逗号,横矩阵;分号,竖矩阵 a = [1 2 3],a = [1 ;2 ;3]
% a = 1:0.1:10  头:步长:尾
%L = length(X) 返回 X 中最大数组维度的长度
%c = a .* b 两个矩阵各项相乘,规模要一样;直接乘请检查并确保第一个矩阵中的列
%数与第二个矩阵中的行数匹配,a'逆转矩阵,横竖换
% linspace(0, 1, 10)  0-1等差取10个值
% linspace	y = linspace(x1,x2,n) 生成 n 个点。这些点的间距为 (x2-x1)/(n-1)。
%y = logspace(a,b,n) 在 10 的幂 10^a 和 10^b(10 的 N 次幂)之间生成 n 个点
%Y = diff(X) 计算沿大小不等于 1 的第一个数组维度的 X 相邻元素之间的差分
%A = magic(6) 1-6^2,每行,对角线和一样
%A(1:2,:) 第1,2行 B=A(:,[1,4,5,6]) 第1,4,5,6列
%B = rand(3) 3*3矩阵,0-1随机数,rand(3,1)3行1列
%一般来说,可以使用公式 r = a + (b-a).*rand(N,1) 生成区间 (a,b) 内的 N 个随机数。
%X = randi(imax,n) 返回 n×n 矩阵,其中包含从区间 [1,imax] 的均匀离散分布中得到的伪随机整数。
%X = randi(imax,sz1,...,szN) 返回 sz1×...×szN 数组,其中 sz1,...,szN 指示每个维度的大小。例如,randi(10,3,4) 返回一个由介于 1 和 10 之间的伪随机整数组成的 3×4 数组。
% C1 = [A, B] 横着拼起来,长度增加
% C2 = [A ; B] 竖着拼起来,纬度增加
% B = fliplr(A) 返回 A,围绕垂直轴按左右方向翻转其各列。	
% B=flipud(A) 上下翻转
%B(:,3)=[],删掉第三列
% A(:, end:-1:1)	可用于反转矩阵
%I = eye(n) 返回一个主对角线元素为 1 且其他位置元素为 0 的 n×n 单位矩阵。
%X = ones(n) 返回一个 n×n 的全 1 矩阵 X = zeros(n) 返回一个 n×n 的全零矩阵。
%A(:) 将矩阵A转换为列向量
% M = min(A,[],dim) 返回维度 dim 上的最小元素。例如,如果 A 为矩阵,则 min(A,[],2) 是包含每一行的最小值的列向量。
% M = mean(A,dim) 返回维度 dim 上的均值。例如,如果 A 为矩阵,则 mean(A,2) 是包含每一行均值的列向量。
% tf = strncmpi(s1,s2,n) 比较 s1 和 s2 的前 n 个字符,忽略字母的任何大小写差异。

% 二.读取和显示
% disp([name,' will be ',num2str(age),' this year.'])	展示一个向量,num2str将数字转换为字符串
% str=sprintf("The current time is: %d:%d %s",A1,A2,A3)	
% x = input('What is the original value? ')获取变量数据;
% A = importdata(filename) filename='example.txt' 将数据加载到数组 A 中。
% fprintf(’     %d %3.3f‘,variable1,variable2);	

%三。函数
%inline function C=@(F) (F-32)*5/9;  C(100)  适用于简单的
%function [A,B] = C2F(C,D) %多个输出,只要第一个,直接a,要第二个,[~,b]

% for循环
% for counter = j : m : k 头;步长;尾
% 	statements;
% end

%counter不要用i,i虚数专用 
%  syms x   y=sin(x);  diff(y,x)   y对x求导

% 牛顿解方程法 while循环 打包成专用函数
% function x= Newton_while(x0,f,df)
% while abs(f(x0))>=1e-14
%     x0=x0-f(x0)/df(x0);
% end
% x=x0;
%  fprintf('the value of x and f are %3.3f,%3.3e\n',x0,f(x0));
% end
%如何调用
% f=@(x) -15*x.^3-11*x.^3-2*x.^2+5*x-20;
% df=@(x) -45*x.^2-33*x.^2-4*x+5;
% j=-4:4;
% plot(j,f(j));
% yline(0);
% roots=[];
% l=1;
% for k=-4:0.5:4
%     x0=k;
%    x= Newton_while(x0,f,df);
%     if ~any(abs(roots-x)<1e-6)
%         roots(l)=x;
%         l=l+1;
%     end
% end

% 牛顿法合集
% 1.普通形式
%    x0=0
%    f= @(x) x.^2+sin(x)-5;
%    df=@(x) x*2+cos(x);
%    for j=1:100
%        fprintf('values of x and f are %3.6f, %3.3e \n',x0,f(x0))
%        x=x0-f(x0)/df(x0);
%        if abs(f(x)) <1e-16
%            break
%        else
%            x0=x;
%        end
%    end
%    fprintf('values of x and f are %3.6f, %3.3e \n',x,f(x))
% 2.for func
%     function x=Newtonfunc(x0,f,df) %%避免每次定义f和df,直接从另一个文件取过来
%  x1=x0;
%    for l=1:1:100
%        x=x0-f(x0)/df(x0);
%        if abs(x)<1e-16
%           break;
%        else
%            x0=x;
%        end
%    end
%               fprintf('It takes %d iterations to get the answer\n.',l);
%       fprintf('When the initial number is %.2f, values of x and f are %.3f, %.3e \n',x1,x,f(x));
% 
% end
% 3. while func
% function x=Newtonfunc_while(x0,f,df)
%  x1=x0;
%  x=x0-f(x0)/df(x0);
%  l=1;
%    while abs((x-x0))>1e-16
%        x0=x;
%        x=x0-f(x0)/df(x0);
%        l=l+1;
%    end
%       fprintf('When the initial number is %.2f, values of x and f are %.3f, %.3e \n',x1,x,f(x))
%       fprintf('It takes %d iterations to get the answer\n.',l);
% 4.如何筛选非重复根
% f=@(x) x.^5-2.*x.^4-10.*x.^3+20.*x.^2+9.*x-18;
%  df=@(x) 5.*x.^4 - 8.*x.^3 - 30.*x.^2 + 40.*x + 9;
%  k=0;
%  roots=[];
% for j=-4:0.5:4
%     x=Newtonfunc_while(j,f,df);
%     if ~any(abs((roots-x))<1e-5)
%             k=k+1;
%         roots(k)=x;
%     end
% end


% addpatch('函数文件夹地址')
% save 文件名 B   Load
%vpa 增加计算精度

% if <expression 1> 
% 	<statement(s)> 
% elseif <expression 2> 
%  	<statement(s)> 
% elseif <expression 3> 
%  	<statement(s)> 
% else 
% 	<statement(s)> 
% end

%while 循环
% while condition
% 	statements;
% end

%any(abs(roots-x)<1e-6) any 只要有一个成立就是1

% Food='Pizza';
% switch lower(Food) lower 全变小写
%     case {'Pizza','hamburger'}  多个条件符合一个即可
%         disp('Junk but delicious.')
%     case 'noodle'
%         disp('Chinese people usually eat noodle on their Birthday')
%     case 'dumpling'
%         disp('My favorite!')
%     otherwise
%         disp('Can you suggest any others?')
% end

%画图
% - 实线  --虚线   :点线     -.点划线

% 'o'	圆圈'+'	加号'*'	星号'.'	点'x'	叉号'_'	水平线条
% '|'	垂直线条's'	方形'd'	菱形'^'	上三角'v'	下三角'>'	右三角'<'	左三角
% 'p'	五角形'h'	六角形

% % y黄色m品红色c青蓝色r红色g绿色b蓝色w白色k黑色

%数据处理与画图
% D=importdata('Monthly_mean_Sargassum_biomass_2011_2018.txt'); %../lesson5/···.txt 相对路径
% Data=D.data;  %data只读只含有数值的行/列
% header=D.colheaders;

% for j=1:length(header)
%     if strncmpi(header{j},'year',4)  %前几个相同 ,strcmp 两个字符串完全一样
%         iYear =j;
%     elseif strncmpi(header{j},'Month',5)
%         iMon=j;
%     elseif strncmpi(header{j},'Mean_bio',8)
%         iData=j;
%     end
% end
% 
% Mon=Data(:,iMon);
% Year=Data(:,iYear);
% Biomass=Data(:,iData);
% 
% TPC=Biomass*0.0543*1e12/12;
% 
% rCarb2ww=[0.161,0.093,0.097,0.061,0.043,0.102,...  %换行
%     0.097,0.097,0.214,0.091,0.076,0.056,0.149]
% %mean(,2) 行取平均
% 
% for kk=1:length(rCarb2ww);
%     rr=rCarb2ww(kk);
%     PIC(:,kk)=Biomass*rr*1e12/100;
%     POC(:,kk)=TPC-PIC(:,kk);
%     PIC2POC(:,kk)=max(PIC(:,kk)./POC(:,kk));
% end
% 
% x=1:length(PIC);
% mPIC=mean(PIC*12*1e-12,2)' ;
% minPIC=min(PIC*12*1e-12,[],2)' ;
% maxPIC=max(PIC*12*1e-12,[],2)' ;
% 
% mPOC=mean(POC*12*1e-12,2)' ;
% minPOC=min(POC*12*1e-12,[],2)' ;
% maxPOC=max(POC*12*1e-12,[],2)' ;
% 
% figure(1)
% 
% x2=[x,fliplr(x)] %flip.矩阵左右相反
% inBetween=[minPIC,fliplr(maxPIC)];
% h1=fill(x2,inBetween,[0.9 0.9 0.9]) %0.9 rgb代码,0-1之间
% hold on
% plot(x,mPIC,'color',[0.5,0.5,0.5],'LineWidth',2);
% hold off
% pbaspect([2,1,2])% 图表三维比例,长宽高
% xticks([0:12:96])% x轴刻度值
% xticklabels({'2011','2012','2013','2014','2015','2016','2017','2018','2019'})
% ylim([-0.1 1.1])%设置y轴范围
% yticks([0:0.25:1])
% yticklabels({'0.00','0.25','0.50','0.75','1.00'})%y轴刻度标签
% legand([h1,h2],'PIC','POC','Location','northwest') %设置图例
% ylable('Mt Carbon')%y轴名字
%title('My Title') 标题

%fill([-1,0,1,0],[0,-1,0,1],'r') x,y,颜色 逆时针给四个坐标
% x=-5:0.05:5;
% f=@(x) sin(x)
% plot(x,f(x));
% hold on
% fill([0,pi/2,pi/2,0],[0,0,1,1],'r')

%grid on 显示网格线
% subplot(m,n,p) 将当前图窗划分为 m×n 网格,并在 p 指定的位置创建坐标区
%semilogx/y 在 x/y 轴上使用以 10 为底的对数刻度、在 y/x 轴上使用线性刻度来绘制 x 和 y 坐标。
%loglog(X,Y) 在 x 轴和 y 轴上应用以 10 为底的对数刻度来绘制 x 和 y 坐标

%errorbar(x,y,yneg,ypos,xneg,xpos) 绘制 y 对 x 的图,并同时绘制水平和垂直误差
%example
%subplot(2,1,1);
%x=linspace(0,10,10);
%y=sin(x./2);
%err=0.3*ones(size(y));
%subplot(2,1,2);
%errorbar(x,y,err);
% figure
% x=linspace(0,5,20)
% y=3*x.^2+x-5;
% perry=0.1*rand(1,length(x)).*y;
% nerry=0.1*rand(1,length(x)).*y;
% perrx=0.1*rand(1,length(x)).*fliplr(x);
% nerrx=0.1*rand(1,length(x)).*fliplr(x);
% errorbar(x,y,nerry,perry,nerrx,perrx,'o') 垂直误差下上,水平误差左右
% title('Errorbar Plot')

% plot([x1,x2],[y1,y2]) 绘制直线,也可以绘制封闭图形(顺时针给坐标)
% plot([1,1],[0,2],'k','LineWidth',2);
% fplot(@(x) sin(1./x),[0.01 0.5]) 电脑自己给x点,画的好

% v = get(h) 返回 h 标识的图形对象的所有属性和属性值。
% v = get(h,propertyName) 返回特定属性 propertyName 的值。使用时须用单引号将属性名引起来,例如,get(h,'Color')。
% set(H,Name,Value) 为 H 标识的对象指定其 Name 属性的值。使用时须用单引号将属性名引起来,例如,set(H,'Color','red')。
% gca  当前的图或坐标区
%( x = 0:pi/20:2*pi;
% plot(x, sin(x))
% hold on
% plot(x, exp(-0.1*x).*sin(x), 'o')
% hold off
% hkids = get(gca, 'child');
% set(hkids(1), 'marker','^')
% set(hkids(2), 'linewidth',3))
% 重要的句柄:
% color 颜色
% linestyle 
% linewidth
% marker   标记物
% MarkerEdgeColor
% MarkerFaceColor
% MarkerSize
% children 获得所有子对象
%text(x,y,txt) 使用由 txt 指定的文本,向当前坐标区中的一个或多个数据点添加文本说明。若要将文本添加到一个点,请将 x 和 y 指定为以数据单位表示的标量。若要将文本添加到多个点,请将 x 和 y 指定为长度相同的向量。

%child example
% x=0:pi/20:2*pi;
% hsin=plot(x,sin(x));
% set(hsin,'LineWidth',4);
% get(hsin)
% x=0:pi/20:2*pi;
% plot(x,sin(x));
% hold on
% plot(x,exp(-0.1*x).*sin(x),'o')
% hold off
% hkids=get(gca,'child');
% set(hkids(1),'marker','^')
% set(hkids(2),'linewidth',3)
% get(hkids(1))
 
%画两个y轴的图
% x=-5:0.5:5;
% y=sin(x);
% z=cos(x);
% figure(1)
% plot(x,[y;z])
% legend('sin(x)','cos(x)','Location','NorthEastOutside') % 加上outside,图例在图片外部创建
% figure(2)
% [ax,h1,h2]=plotyy(x,y,x,z);%画两个y轴
% legend([h1,h2],{'sin(x)';'cos(x)','location','best'})
% hh1=get(ax(1),'ylabel');
% set(hh1,'string','sin(x)')
% set(ax(1),'ytick',[-1.2:0.2:1.2])
% set(ax(1),'YGrid','on')
% set(ax(1),'XColor','k','YColor','b') %x,y轴颜色
% set(h1,'linestyle','none','Marker','s','MarkerFaceColor','k','markeredgecolor','m')%不区分大小写
% hh2=get(ax(2),'ylabel');
% set(hh2,'string','cos(x)')
% set(ax(2),'ytick',[-1.2:0.2:1.2])
% set(ax(2),'yGrid','on')
% set(ax(2),'xGrid','on')
% set(ax(2),'XColor','k','YColor','r')
% set(h2,'linestyle','-','Marker','o','MarkerFaceColor','r','markeredgecolor','g')

%[X,Y] = meshgrid(x,y) 基于向量 x 和 y 中包含的坐标返回二维网格坐标。X 是一个矩阵,每一行是 x 的一个副本;Y 也是一个矩阵,每一列是 y 的一个副本。坐标 X 和 Y 表示的网格有 length(y) 个行和 length(x) 个列。
%mesh(X,Y,Z)  三维网格图
%colorbar 在当前坐标区或图的右侧显示一个垂直颜色栏
%contour(x,y,z);%等值线图 不加x和y会使得坐标范围指数放大 
%contour(x,y,z,10);%画十条等值线
%contourf 等价于contour+fill
%contourf(X,Y,Z) 指定 Z 中各值的 x 和 y 坐标。
%clabel(C,h) 为当前等高线图添加标签,将旋转文本插入每条等高线。
%caxis([0 0.8])设置颜色图范围
%imshow() 使读入的图片变成RGB矩阵

%矢量图quiver
% [x,y]=meshgrid(-2:.2:2,-2:.2:2);
% V=x.^2+y;
% dx=2*x;
% [nx,ny]=size(x);
% dy=ones(nx,ny);
% contour(x,y,V);
% hold on;
% quiver(x,y,dx,dy) %dx dy类似速度
% hold off;
% 用surf 命令达到和mesh类似的效果

% [x,y]=meshgrid(-8:0.5:8);
% r=sqrt(x.^2+y.^2)+eps;
% z=sin(r)./r;
% mesh(z);
% saveas(gca,'1.png')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值