MATLAB实验报告 下载本文

x=input('please input x:'); y=0; if x<0 y=0; elseif x<1 y=x; elseif x<=2 y=2-x; else y=0 end

结果:please input x:-3

ans =0

please input x:2^(1/2) ans =0.5858

please input x:inf y=0

ans = 0

3.用 for 循环语句实现编写一个求n 阶乘的函数文件 1、函数文件设计:

设计一个函数文件实现一个阶乘运算y(n)?n!?1?2?3???(n?1)?n,

并设计程序调用该函数。

为保证函数的通用性,当输入负数或小数时,显示出错提示: disp('Input parameter must be a positive integer!') 提示:fix(x) 对零方向取整数 ceil(x) 对+?方向取整数

round(x) 四舍五入取整数 程序:function [y] = WFSSY23(n )

%UNTITLED3 Summary of this function goes here % Detailed explanation goes here x=input('please input x:'); if x<0|(fix(x)~=x)

disp('Input parameter must be a positive integer!');

end y=1; for x=1:1:x y=y*x;

end

结果:please input x:3

ans = 6

9

please input x:4 ans =24

4.找到一个 n!> 10100 的值(利用上题的n阶乘函数文件) 程序:function [y ] = WFSSY24( n )

%UNTITLED4 Summary of this function goes here % Detailed explanation goes here x=input('please input x:'); if x<0|(fix(x)~=x)

disp('Input parameter must be a positive integer!');

end y=1;

for x=1:1:x y=y*x;

end

if y>10^100 y;

else

disp('n!<10^100!');

end

结果:please input x:5

ans =120

please input x:9999 n!>10^100! ans =Inf

5.已知一维数组 A = [2,4,5,8,10]、B =[4,9,6,7,4],用for 循环语句实现和函数可用sum()

程序:function [s,c ] = WFSSY25(i,n )

%UNTITLED2 Summary of this function goes here % Detailed explanation goes here A = [2,4,5,8,10]; B =[4,9,6,7,4];

n=input('please input n:'); fori=1:1:n

c=A(i)*B(n-i+1); end s=sum(c) end

?ABii?1nn?i?1,求

结果:please input n:3

s = 20

6.编写验证魔方矩阵的函数文件,输出要求如下: (1)如果输入矩阵的维数小于3,输出显示’error’

10

(2)如果输入矩阵的不是方阵,输出显示’the size of matrix X mustbe N-by-N matrix’ (3)显示行、列和及其对角线求和后的值,并判断其和是否相同。若不同,显示‘No’,相同显示‘Yes’。

程序: function [ b,m,n,c,d,p,e,f,j,h,i ] = WFSSY26( A ) %UNTITLED3 Summary of this function goes here % Detailed explanation goes here A=input('Enter matrix A=>'); b=ndims(A);

[m,n] = size(A); if b<3

disp('error') ; end if m~=n

disp('the size of matrix X must be N-by-N matrix'); end

c=sum(A,1); d=sum(A,2); p=diag(A);

e=diag(fliplr(A)); f=sum(c)/m; g=sum(d)/n; h=sum(p); i=sum(e); if f==g; if h==i if f==h disp('Yes') else

disp('No') end else

disp('No') end else

disp('No') end

结果:Enter matrix A=>[17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9] error

11

Yes ans =2

Enter matrix A=>[17 24 5 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9] error No

ans =2

实验三MATLAB 的图形绘制

一、实验目的及要求:

1.掌握MATLAB 绘图的基本方法,熟悉各种绘图函数的使用; 2.掌握图形的修饰方法和标注方法; 3.了解MATLAB 中图形窗口的操作。

二、实验内容:

x=[-2π,2π],y1=sinx、y2=cosx、y3=sin2x、y4=cos 2x

①用MATLAB语言分四个区域分别绘制的曲线,并且对图形标题及横纵坐标轴进行标注。 程序:

closeall clc

x=[-2*pi:pi/1000:2*pi]; y1=sin(x); y2=cos(x); y3=sin(2*x); y4=cos(2*x); subplot(2,2,1) plot(x,y1);

axis([-2*pi 2*pi -1 1]) set(gca,'xtick',-2*pi:pi:2*pi) set(gca,'ytick',-1:0.5:1)

set(gca,'xticklabel','-2pi|-pi|0|pi|2pi') set(gca,'yticklabel','-1|-0.5|0|0.5|1') xlabel('x');ylabel('y1'); title('sin(x)'); gridon; subplot(2,2,2)

axis([-2*pi 2*pi -1 1])

12