【MATLAB】常用命令快速入门,国赛加油 (2)

相关知识点: input、for循环或 while循环、disp

N = input("请输入数列的项数:"); res = [1,1]; for i = 3:N element = res(length(res)) + res(length(res) - 1); res = [res,element]; end disp(res); % 输出斐波那契数列 圆中四只鸭子在同一个半圆的概率

参考思路:蒙特卡罗法(进行N次试验,每次试验生成4个随机点,统计四点在同一个半圆的个数)

相关知识点: input、if...else、for循环或while循环、rand、disp

函数、匿名函数和脚本 函数 % function [输入参数] = myfun(输入参数) % 函数体 % end x = area(2); function s = area(r) % 圆的面积 s = pi*r.^2; end 匿名函数 % f = @(输入参数) 函数体 % f:函数句柄 f = @(x) x.^2; f(2) % 4 f([2,3]) % [4,9] f1 = @(x, y) x.^2 + y.^2 + 2*x.*y; f1(2,3) % 25 f1([1,2,3], 6) % [49, 64, 81] 匿名函数和函数的转化 f2 = @fun; % 方式一 f2(5) % 25 f3 = @(x)fun(x); % 方式二 f3(6) function y = fun(x) y = x.^2; end 使用场景 % 函数体复杂时,使用函数 % 函数体简单时,使用匿名函数 f4 = @fun1; f4(-5); f5 = @(x)fun1(x); f5(-4) f6 = @fun2; f6(5,2) function y = fun1(x) if x>=0 y = x; else y = -x; end end function y = fun2(x,a) if x>=a disp("x大于等于a") else disp("x小于a") end end 脚本

实际上就是后缀.m的文件;

当文件里只有函数时,就成为函数脚本文件或函数文件;

函数文件可被其他脚本调用(需要在同一文件目录下),也可在命令行调用。

value = input("请输入矩阵元素范围[min,max]:"); sz = input("请输入矩阵行列数[row,col]:"); isInt = input("请指定元素类型 0) 小数 1) 整数:"); m = GetMatrix(isInt, value, sz) disp(m)

GetMatrix.m

function y = GetMatrix(isInt, val, size ) rand('seed',0); % 加入随机种子使得每次获得的结果一致 if isInt == 0 y = (val(2) - val(1)) * rand(size) + val(1); else y = randi(val,size); end end MATLAB绘图操作 基本绘图命令plot

二维绘图命令plot
绘制 y = sin(x)

x = linspace(0,2*pi,100); y = sin(x); plot(x,y);

image

一幅图绘制多条曲线

% 方式一:hold % hold on 开启图形保持功能,绘制我个图形对象 % hold off 关闭图形保持功能 x = linspace(0,2*pi,100); y = sin(x); y2 = cos(x); plot(x,y); hold on plot(x,y2); hold off

image

% 方式二:plot(x1, y1, x2, y2, ……) plot(x,y,x,y2);

image

添加坐标轴标签(lable)、标题(title)、图例(legend)

plot(x,y,x,y2); xlabel('x'); ylabel('y = sin(x), y2 = cos(x)'); title('y = sin(x), y2 = cos(x)'); legend('y = sin(x)', 'y = cos(x)');

image

绘制多幅图 figure

x = linspace(0,2*pi,100); y = sin(x); y2 = cos(x); figure; plot(x,y); figure; plot(x,y2);

image

绘制多个子图 subplot

% subplot(m,n,i):m行n列 第i个图形 x = linspace(0,2*pi,100); y = sin(x); y2 = cos(x); y3 = x.^2; y4 = x.^0.5; subplot(2,2,1);plot(x,y); subplot(2,2,2);plot(x,y2); subplot(2,2,3);plot(x,y3); subplot(2,2,4);plot(x,y4);

image

绘图修饰 % plot(x, y, '- r o') 线型、颜色、描点类型(顺序可变) %线型; -实线、--虚线、:点线、-.点画线 %描点类型: .点、。圆、x叉号、+加号、*星号 % <、>、^、v、(三角形的朝向) % s方形、d菱形、p五角星、h六角星 %颜色: r红色、g绿色、b蓝色、y黄色、w白色、k黑色 % plot(x, y, '- r o') 线性、颜色、描点类型(顺序可变) x = linspace(0, 2*pi, 30); y = sin(x); plot(x,y, '- r o');

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwydsz.html